Can't get POST data using NodeJS/ExpressJS and Postman

user2923322 picture user2923322 · Jan 31, 2017 · Viewed 26.8k times · Source

This is the code of my server :

var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());

app.post("/", function(req, res) {
    res.send(req.body);
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

From Postman, I launch a POST request to http://localhost:3000/ and in Body/form-data I have a key "foo" and value "bar".

However I keep getting an empty object in the response. The req.body property is always empty.

Did I miss something?enter image description here

Answer

R. Gulbrandsen picture R. Gulbrandsen · Jan 31, 2017

Add the encoding of the request. Here is an example

..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
..

Then select x-www-form-urlencoded in Postman or set Content-Type to application/json and select raw

Edit for use of raw

Raw

{
  "foo": "bar"
}

Headers

Content-Type: application/json

EDIT #2 Answering questions from chat:

  1. why it can't work with form-data?

You sure can, just look at this answer How to handle FormData from express 4

  1. What is the difference between using x-www-form-urlencoded and raw

differences in application/json and application/x-www-form-urlencoded