Reputation: 305
when i post json data on node server, it leads to error 'Response to preflight request doest't pass access control check' but when i post same request on php server it works . browser console picture
can someone tell me why this not working in node.js but when i tried to post data through postman on node server now no error it works.
here is my nodeJS code
const express = require('express');
const app = express();
app.use(express.json());
app.post('/post', function(req, res){
res.header('Access-Control-Allow-Origin', '*');
res.send(req.body);
})
and this is request code that is send from browser
function callAjax(){
jQuery.ajax({
method: 'POST',
url:'http://localhost:3010/post',
"headers": {
"content-type": "application/json"
},
data: {
email:'[email protected]'
},
success: function(data){
console.log(data);
},
error: function(err){
console.log(err);
}
});
}
Upvotes: 1
Views: 2033
Reputation: 2864
You have to use body-parser.
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/post', function(req, res){
res.setHeader('Access-Control-Allow-Origin', '*');
res.json(req.body);
});
Upvotes: 3
Reputation: 1007
use cors module first:-
npm install --save cors
var cors = require('cors')
app.use(cors())
Upvotes: 1