node.js – Express.js req.body undefined
Table of Contents
node.js – Express.js req.body undefined
UPDATE July 2020
express.bodyParser()
is no longer bundled as part of express. You need to install it separately before loading:
npm i body-parser
// then in your app
var express = require(express)
var bodyParser = require(body-parser)
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post(/login, urlencodedParser, function (req, res) {
res.send(welcome, + req.body.username)
})
// POST /api/users gets JSON bodies
app.post(/api/users, jsonParser, function (req, res) {
// create user in req.body
})
See here for further info
original follows
You must make sure that you define all configurations BEFORE defining routes. If you do so, you can continue to use express.bodyParser()
.
An example is as follows:
var express = require(express),
app = express(),
port = parseInt(process.env.PORT, 10) || 8080;
app.configure(function(){
app.use(express.bodyParser());
});
app.listen(port);
app.post(/someRoute, function(req, res) {
console.log(req.body);
res.send({ status: SUCCESS });
});
Latest versions of Express (4.x) has unbundled the middleware from the core framework. If you need body parser, you need to install it separately
npm install body-parser --save
and then do this in your code
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())
node.js – Express.js req.body undefined
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.
Related posts on node.js :
- node.js – Does Redis uses indexes to get the data?
- node.js – Make pm2 log to console
- node.js – LRU Cache in Node js
- node.js – How to specify node version in heroku
- node.js – How can I execute a bin with yarn?
- node.js – Angular 2 accessing mongoDB data
- node.js – Retries in AWS Lambda
- node.js – npm install from tgz created with npm pack