Express js req.body returns empty
I tried all solutions from some other stackoverflow posts, but that didn't solve my problem.
Here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var index = require('./routes/index');
var v1 = require('./routes/route');
app.use('/', index);
//routes for api
app.use('/v1',v1);
Here is my controller post
module.exports = {
createUser:function (req,res) {
console.log(req.body);
res.send('ok'+req.body.test);
}
}
req.body
returns {}
even if the request body contains parameters.
I am testing api with postman plugin.
Update
Postman request
source to share
The bodyParser object provides various factories for creating intermediate products. All mediators will populate the property with a req.body
parsed body or an empty object {}
if there was no body to parse (or an error was returned).
app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies
The new body object containing the parsed data is filled with the request object after the middleware
req.body
will contain the parsed data, this object will contain the key-value pairs where this value can be a string or an array
Content-type application/x-www-form-urlencoded
app.use(bodyParser.json()); // for json encoded bodies
The new body object containing the parsed data is populated with the request object after the middleware (i.e.
req.body
).
Content-type application/json
application/json
used when you send data {"test":"hello"}
like this. www-form-url-encoded
used to get data as key value in object from url when used app.use(bodyParser.urlencoded({ extended: true }));
. They are both different and have their own use cases.
source to share
After removing the last 4 lines of code (to set up routes correctly) and adding test lines:
app.post('/ping', function (req,res) {
console.log(req.body);
res.send('ok ' + req.body.test);
});
let server = http.createServer(app);
server.listen(8899, function onstart() {
console.log('server listening');
});
When I run:
curl -X POST http://localhost:8899/ping -d '{"test": 1234}'
I get ok undefined
as you do. After adding the correct header content-type
:
curl -X POST http://localhost:8899/ping -d '{"test": 1234}' -H "content-type: application/json"
it works like a charm and i get ok 1234
. So I think you are missing a title "content-type: application/json"
in your postman.
source to share