before anything else, I want to say, that I have read about 12 similar questions on the StackOverflow, but none of them helped me to solve my issue and most of them had pretty unclear answers, so I believe that this question is worth asking, also I'm just a beginner.
Environment:
I have a react app running on localhost
on port 3000
and an Express server on port 8000
. My server:
const express = require('express');
const app = express();
const port = 8000;
app.post('/register', (req, res) => {
res.send(JSON.stringify({test: 'HELLO!'}));
});
const server = app.listen(port, () => console.log('Listening on port', server.address().port));
And client:
static register(username, password) {
return fetch('http://localhost:8000/register', {
method: 'POST',
body: JSON.stringify({username, password}),
headers: {'Content-Type': 'text/plain'}
}).then(response => console.log(response));
}
When sending this request I would get this error message:
Failed to load http://localhost:8000/register: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
After some research I tried some solutions: Adding this middleware before "POST" on my server:
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
It didn't help, so I've tried node CORS package and still, it didn't solve my issue. But something has changed: I was no longer getting this error message instead, I would get the response logged, but instead of getting an object that I have sent from the server, I was getting some kind of 'error object':
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:8000/register"
But, when I opened a network tab in Chrome, I saw that the response was what I expected {test: HELLO!}
, so Chrome was changing something, so I have disabled Chrome security, but it still was logging the same error object. So after trying all of this, I couldn't make my code work, so can anyone fully answer how to send requests from React app to the express server without getting cors error?
Full server code:
const express = require('express');
const cors = require('cors');
const app = express();
const port = 8000;
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.post('/register', (req, res) => {
res.send(JSON.stringify({test: 'HELLO!'}));
});
const server = app.listen(port, () => console.log('Listening on port', server.address().port));