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.
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:
You sure can, just look at this answer How to handle FormData from express 4
x-www-form-urlencoded
and raw
differences in application/json and application/x-www-form-urlencoded