2

I am working on a management system, currently creating the POST requests for the api. I need the values of the request's body to post a new city in the database. The values are used in the stored procedure as parameters. Instead of the key's values which I entered, I am getting an "undefined" value, sometimes a "[object Object]".

I am using a MySQL server, hosted in the cloud by Google's services. Backend is made with Node.js, routing with Express. None of my attempts to fix the bug worked for me.

What I've tried so far:

-Parsing each key's value .toString() and JSON.stingfify() from the body

-Converting the body to Json/string, then back to a javascript object

-Getting the response's requests's body (res.req.body)

-Getting the body's response values in an array, then pushing the next element after it has been passed as a parameter to the stored procedure

-Using the 'request' npm extension to put the values I need when calling the POST method.

-Changed the values to be stored in the URL' parameters instead of the body.

-Sent the body's values as form-data, JSON file, HTML page

Controller method in cityController.js:

exports.city_post = (req, res, next)=>{
  poolDb.getConnection(function (err, connection){
      if(!err) {
        const sql = 'CALL createNewCity(?,?)';
        var zipReq = req.params.zip; 
        var nameReq = req.params.name;
        var reqBody = JSON.stringify(req.res.body);
        connection.query(sql,[zipReq,nameReq], (err,rows)=>{
            if(!err){
                return res.status(201).json({Message: 'City with name: '+nameReq+' and zip code: '+zipReq+' created successfully\n', rows});
            }    
            else{
                return res.status(404).json({errorMessage: err})
            }
        });
        }
    else{
        return res.status(500).json({errorMessage: "server error: "+this.err});
    }
    console.log("\nZip Code: "+ zipReq +"\nName: " + nameReq); //for testing 
    console.log("\nrequest body: " + reqBody); //for testing
  });
}

City route:

const express = require('express');
const router = express.Router();
const CityController = require('../controllers/cityController.js');

router.get('/', CityController.city_getAll);

router.get('/:cityzip', CityController.city_getbyzip);

router.post('/add', CityController.city_post);

...

module.exports = router;

Expected: Posting a new field in table city, status code (201).

Actual: Status code (404), no new insertion in the DB. body, req.body.zip & req.body.name are of value "undefined".

Screenshots:

-Terminal output: https://i.stack.imgur.com/l3V24.jpg

-Postman request: https://i.stack.imgur.com/05w4N.jpg

bojkel
  • 63
  • 2
  • 10
  • Try console.logging out the req.params/req.query properties to see what they contain if anything. Might be formatted in an unexpected way especially having received an "[object Object]". – Gavin Aug 23 '19 at 11:11

1 Answers1

2

Express doesn't parse post body by default (for some reason). You can try popular body-parser npm package, or collect the raw body data and parse from a string yourself if you don't want to add a whole new package. Here as express app:

app.use(function(req, res, next){
    var data = "";
    req.on('data', function(chunk){ data += chunk})
    req.on('end', function(){
        req.rawBody = data;
        var json = JSON.parse(req.rawBody); // assuming valid json. ideally check content-type first
        next();
    });
});
Gavin
  • 2,214
  • 2
  • 18
  • 26
  • 1
    Good answer. But why create your own body parser when the body-parser middleware package has been thoroughly debugged and handles various body formats transparently? https://expressjs.com/en/resources/middleware/body-parser.html – O. Jones Aug 23 '19 at 11:01
  • 1
    @O.Jones very true in fairness. Surprised it's not been folded into express by now to be honest. – Gavin Aug 23 '19 at 11:09
  • Thanks for sharing, thats clever. I already tried something similar but it didn't work. Both creating my own parsing function and using the body-parser extension. – bojkel Aug 23 '19 at 11:13
  • 1
    2022 update: In Express ^4.16 installing body-parser is redundant. Express can now handle data from the body using express.json() and express.urlencoded(). Credits to Jan Peša for his answer: https://stackoverflow.com/a/24344756/8681915 – bojkel Sep 30 '22 at 12:42