I have this as configuration of my Express server
app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: \"keyboard cat\" }
No. You need to use app.use(express.bodyParser())
before app.use(app.router)
. In fact, app.use(app.router)
should be the last thing you call.
I solved it with:
app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
});
If you are using some external tool to make the request, make sure to add the header:
Content-Type: application/json
Looks like the body-parser is no longer shipped with express. We may have to install it separately.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!
Refer to the git page https://github.com/expressjs/body-parser for more info and examples.
Use app.use(bodyparser.json()); before routing. // . app.use("/api", routes);
You can try adding this line of code at the top, (after your require statements):
app.use(bodyParser.urlencoded({extended: true}));
As for the reasons as to why it works, check out the docs: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions