Express req.body is empty when using the http.post

Viewed 790

I do not know why the req.body is EMPTY... app.js use the body-parser middleware(http://www.expressjs.com.cn/4x/api.html#req.body)

var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// add baseurl
app.use('/api', index);
app.use('/api', users);

user.js

router.route('/user')
.post(function (req, res, next) {
    console.log(req.body);
    console.log(req.headers);
    //console.log(JSON.parse(Object.keys(req.body)[0]));
    res.json({title: 'RESTful: POST...'});
});

I have printed the headers: But the req.body is empty and I used the JSON.parse(Object.keys(req.body)[0]) to parse the result from the other similar question, but it did not work to me. I use the postman to request the POST,

{ 'cache-control': 'no-cache',
'postman-token': 'db7766d7-767c-4d33-be3a-acfa18ac1d9c',
'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'PostmanRuntime/6.4.1',
accept: '*/*',
host: 'localhost:3000',
'accept-encoding': 'gzip, deflate',
'content-length': '0',
connection: 'keep-alive' }

postman screenshot

2 Answers

Your routes seem to be configured correctly. I'd rule out any funny business with postman by trying to make the same request using curl.

curl -d "@/path/to/payload.json" -H "Content-Type: application/json" -X POST http://localhost:3000/api/user

What happens then?

EDIT: From what I gather in the comments, it looks like the request you were posting contained a Content-Type: application/x-www-form-urlencoded header, but with a JSON body {"name":"user"}. In other words, the content-type header and the body are mismatched.

Because the server was expecting URL encoded content, it would have been unable to parse the request body. For that reason, it's important to make the Content-Type header agree with body format. So in this case, you have two options.

  1. Keep Content-Type: application/x-www-form-urlencoded and change the body to name=user
  2. Change your header accordingly to Content-Type: application/json and keep the body as {"name":"user"}
Related