The JSON data in request body is not getting parsed using body-parser
In express.js the order in which you declare middleware is very important. bodyParser
middleware must be defined early than your own middleware (api endpoints).
var express = require('express'); var app = express();var router = express.Router();var bodyParser = require('body-parser');app.use('/', express.static(__dirname));app.use(bodyParser.urlencoded({ extended: false }));app.use(bodyParser.json()); // support json encoded bodiesrouter .route('/newUser') .post(function(req, res) { console.log(req.body); });app.use('/api', router);app.listen(8080);
Change the request header
'Content-Type':'application/json'
So that bodyParser can parse the body.
*That is what works for me. i am using angular 2+ with express(body-parser)
I spent quite a bit of time trying to figure out how to pass objects from Axios as key-value pairs and eventually decided to go with an alternative because setting the Content-Type: "application/json" retuned an empty object.
If the above options don't work for you, I would consider:
- Extracting the key (which should contain the entireobject)
- Parsing the key
- Accessing the values of the newly created objects
This worked for me:
var obj = (Object.keys(req.body)[0])
var NewObj = JSON.parse(obj)
var name = apiWords["Key1"]
var image = apiWords["Key2"]