Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js req.body undefined

I have this as configuration of my Express server

app.use(app.router);  app.use(express.cookieParser()); app.use(express.session({ secret: "keyboard cat" })); app.set('view engine', 'ejs'); app.set("view options", { layout: true }); //Handles post requests app.use(express.bodyParser()); //Handles put requests app.use(express.methodOverride()); 

But still when I ask for req.body.something in my routes I get some error pointing out that body is undefined. Here is an example of a route that uses req.body :

app.post('/admin', function(req, res){     console.log(req.body.name); }); 

I read that this problem is caused by the lack of app.use(express.bodyParser()); but as you can see I call it before the routes.

Any clue?

like image 343
Masiar Avatar asked Feb 07 '12 13:02

Masiar


2 Answers

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' }); }); 
like image 73
Mark Bonano Avatar answered Sep 30 '22 19:09

Mark Bonano


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()) 
like image 34
Jay Avatar answered Sep 30 '22 20:09

Jay