1

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.

postman picture

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);
    }
   });
 }

2 Answers 2

3

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

still got error 'No 'Access-Control-Allow-Origin' header is present on the requested resource.'
@IftikharHussain, I haven't seen the code before. Use res.setHeader instead of res.header. I have edited answer. Please check it. REF: stackoverflow.com/questions/18310394/…
1

use cors module first:-

npm install --save cors
var cors = require('cors')
app.use(cors())

5 Comments

not working but now error changes on client side ' Failed to load localhost:3010/post: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost' is therefore not allowed access. The response had HTTP status code 400.'
app.use(cors()) should be placed at top
now request sent with no error but return nothing. but when i app.use(express.json()); uncomment it show me 400 bad request
try res.json(req.body) instead res.send(req.body) & if it solves accept my awnser
also use body-parser as someone has suggested in awnser to get (body)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.