How to Enable CORS from Nodejs server

buydadip picture buydadip · Oct 12, 2016 · Viewed 9.8k times · Source

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

Shubham Khatri picture Shubham Khatri · Oct 12, 2016

The browser sends a preflight Options requests to the server to check if CORS is enabled on the server. To enable cors on the server side add this to your server code

app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });