MARKAND Bhatt MARKAND Bhatt - 1 year ago 127
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());'/', function(request, response) {
console.log('post hit');
message: 'Post Hit'

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

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

type: "POST",
crossDomain: "true",
url: "http://localhost:8000/",
data: {
"a": "b"
headers: {
"Content-Type": "application/json"
success: function(d) {
error: function(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 Source

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')

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 :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download