Bolboa Bolboa - 1 month ago 9
Node.js Question

fetching POST data from API (node js, react)

I am attempting to make a POST request to my API. The handler currently looks like this...

app.post('/login', function(req, res, next) {
console.log("here");
...
});


This API is hosted on localhost 8080. And I am fetching the data as so...

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


What I am passing is irrelevant for the moment, I just want to make a successful POST request. When I submit the form, it fetches the API, and this is the message I get on the console...

OPTIONS /login 200 8.177 ms - 4


It looks as if something worked, but it did not, the
console.log("here");
never gets called.

I believe I am not calling the API properly. If I remove the headers, the POST call is made, however I believe I need these headers because they are important for passing data to the
response
. What should I do?

Answer

You are likely facing a CORS permissions issue. This will always happen if you're serving your web application from any host (like your local file system) different from the url of the running node server. Browsers limit all ajax access to urls that don't precisely match the protocol, subdomain, domain and even port exactly.

You can host the static HTML/JS/CSS from the node server, and that may solve the problem. Or you could try adding CORS permissions to your node server.

Basically, before your /login route in node add something like the following, assuming you're using express:

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();
});

You can read a lot more about CORS access limitations on MDN or enable-cors.org