0

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.

MARKAND Bhatt
  • 2,428
  • 10
  • 47
  • 80
  • Cross domain error is throw at browser console? The cross domain must be processed in the producer, not consumer. somethink like http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-node-js – BrTkCa Sep 13 '16 at 17:26
  • This endpoint works very fine with POSTMAN. – MARKAND Bhatt Sep 13 '16 at 17:34

3 Answers3

2

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

2

You can also add "Allow-Control-Allow-Origin" extension in chrome to get it run locally. and

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

on the client side to send data.

Anuj Verma
  • 2,519
  • 3
  • 17
  • 23
2

You can enable cors with this node module easily!

const cors = require('cors');
const express = require('express');
const app = express();

app.use(cors());

/* other routes here */
Joakim Ericsson
  • 4,616
  • 3
  • 21
  • 29