MARKAND Bhatt MARKAND Bhatt - 2 months ago 18
Node.js Question

dont get request body in node js rest web api

Following is my nodejs code

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response) {
console.log(request.body);
console.log('post hit');
response.json({
message: 'Post Hit'
});
});

app.listen(process.env.PORT || 8000);


following is my javascript code to call the above post end point

$.ajax({
type: "POST",
crossDomain: "true",
url: "http://localhost:8000/",
data: {
"a": "b"
},
headers: {
"Content-Type": "application/json"
},
success: function(d) {
alert(d);
console.log(d);
},
error: function(e) {
console.log(e);
alert(e);
}
});


I always get my request.body empty in node js.

Sometimes, the rest endpoint is not even hit.

I dont know how this works.

Answer

Enable CORS in express.js

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With')
  res.header('Access-Control-Allow-Headers', 'Content-Type')
  next()
})

also you need to convert your data in json in ajax.

data: JSON.stringify({
    "a": "b"
})

PS : when you test using POSTMAN . it does not send preflight request . that's why it will work in POSTMAN.

Read more about preflight here : https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests