Joss
Joss

Reputation: 555

Cannot access to req.body inside middlewares

I actually have a very tiny app in node.js with Express, and I can't access to req.body.

This is my app.js code:

var express = require('express'),
    middleware = require('./middleware'),
    mysql  = require('mysql'),
    app = express();

app.use(middleware.authenticate);
app.use(middleware.getScope);

app.listen(3000);
module.exports = app;

And the file with the middlewares:

var bcrypt = require('bcrypt'),
    mysql  = require('mysql');

function authenticate(req, res, next){
   console.log(req.body);
    next();
}

function getScope(req, res, next){
    console.log(req.body);
    next();
}

module.exports.authenticate = authenticate;
module.exports.getScope = getScope;

In all cases req.body is undefined.

I'm sending data throw Postman with x-www-form-urlencoded protocol, in this case is a must.

enter image description here

Thanks!!

Upvotes: 5

Views: 1468

Answers (1)

michelem
michelem

Reputation: 14590

You need to add body-parser to express:

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

Check Request here http://expressjs.com/en/api.html

And perhaps a POST route could help too:

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

Upvotes: 5

Related Questions