0

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:'fake@mail.com'
    },
    success: function(data){
        console.log(data);
    },
    error: function(err){
        console.log(err);
    }
   });
 }
Iftikhar Hussain
  • 313
  • 3
  • 14

2 Answers2

2

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);
});
Harish Kommuri
  • 2,825
  • 1
  • 22
  • 28
  • still got error 'No 'Access-Control-Allow-Origin' header is present on the requested resource.' – Iftikhar Hussain May 23 '18 at 09:55
  • @IftikharHussain, I haven't seen the code before. Use `res.setHeader` instead of `res.header`. I have edited answer. Please check it. REF: https://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue – Harish Kommuri May 23 '18 at 10:01
1

use cors module first:-

npm install --save cors
var cors = require('cors')
app.use(cors())
Sanjay
  • 838
  • 1
  • 14
  • 21
  • not working but now error changes on client side ' Failed to load http://localhost:3010/post: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 400.' – Iftikhar Hussain May 23 '18 at 09:58
  • app.use(cors()) should be placed at top – Sanjay May 23 '18 at 10:01
  • now request sent with no error but return nothing. but when i `app.use(express.json());` uncomment it show me 400 bad request – Iftikhar Hussain May 23 '18 at 10:09
  • try res.json(req.body) instead res.send(req.body) & if it solves accept my awnser – Sanjay May 23 '18 at 10:12
  • also use body-parser as someone has suggested in awnser to get (body) – Sanjay May 23 '18 at 10:14