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?