2

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?

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
buydadip
  • 8,890
  • 22
  • 79
  • 154

2 Answers2

3

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();
    });
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

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();
});
Mat J
  • 5,422
  • 6
  • 40
  • 56
  • ok this catches the options request, but the POST request is still not being read, and I kinda need it to pass data. – buydadip Oct 13 '16 at 17:37
  • no Errors, the options request above seems to work. But then my POST handler which comes after OPTIONS handler does not work – buydadip Oct 13 '16 at 18:32