Reputation: 3254
I am using following code, request.body returns {}
i would expect my output as {username:"Mani",password:"pass"}
please help me to fix if anything wrong in this code sample.
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
npm version:
express 4.14.0
body-parser 1.15.2
method: POST
header: Content-Type: application/json
request payload : {username:"Mani",password:"pass"}
output of app.js console is {}
Upvotes: 1
Views: 2873
Reputation: 1021
try this, "content-type": "application/x-www-form-urlencoded", must use this
// chnage content-type to content-type": "application/x-www-form-urlencoded
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
},
"data": {
"name": "mane"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Upvotes: 0
Reputation: 21199
It appears that your body is a json document. You will need to configure body-parser to accept json:
app.use(bodyParser.json());
Upvotes: 1