Bolboa Bolboa - 1 year ago 148
Node.js Question

How to Enable CORS from Nodejs server

I am using react to send data to my API. Every POST request I make gives me an OPTIONS request, and I need to fix this. I think I might need to do some preflight structure but after reading about it I still do not know how to implement it.

At the moment I am connecting to my API as so...

fetch('http://localhost:8080/login', {
method: 'POST',
mode:'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
});


This is called
onSubmit
. I am sending some data to my POST request so I am assuming I need those headers.

Now in my node js server API I have the following handler...

var responseHeaders = {
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
"access-control-allow-headers": "content-type, accept",
"access-control-max-age": 10,
"Content-Type": "application/json"
};

app.post('/login', function(req, res, next) {
if (req.method == "OPTIONS") {
res.writeHead(statusCode, responseHeaders);
res.end();
}
console.log("hello");
...


This does not work however, when I make a request I get...

OPTIONS /login 200 8.570 ms - 4


If I remove the headers the POST works but the data (username, password) is not passed through.

How can I bypass this OPTIONS problem?

Answer Source

app.post is as the name implies, for POST requests. OPTIONS request won't get routed to that method.

You need to write a handler specific for options like so,

app.options("*",function(req,res,next){
  res.header("Access-Control-Allow-Origin", req.get("Origin")||"*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   //other headers here
    res.status(200).end();
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download