i’m currently working on some kind of order system using react for the frontend(port 3000) and express(port 3001) for the backend.
Everything works like a charm as long as i test it on the same macbook that runs the node project. As soon as i test it using a different computer i get the error "Post http://localhost:3001/login net::ERR_Connection_Refused"
The login function looks like this:
fetch("http://localhost:3001/login", {
method: "POST",
headers: {
"accept": "application/json",
"content-type": "application/json"
},
body: JSON.stringify({
em: em,
pw: pw
})
.then ...
i don’t know if it has something to do with cors, which i configured like this in my server.js
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // "*"
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cors());
in my package.json of the React Server i also got this line " "proxy": "https://localhost:3001" but i don’t really know what it does, as i’m fairly new to react development.
I also tried out setting
"Access-Control-Allow-Origin", "*"
i could get API responses like /orders in json format from a different computer but fetch requests from 3000 to 3001 are still not working.
Maybe you guys got some ideas what the problem could be. Maybe it lies somewhere completely different than the code i shared.
Many thanks in advance!
I experimented around with the proxy line in the package.json as well as with cors but i’m not really sure if this is the problem.
2
Answers
This indeed sounds like a cors problem (which are extremely annoying). You can try adding the proxy like you said in your package.json. Then change the fetch to the following:
React should then fetch through the proxy to http://localhost:3001/login
It usually indicates that the server is not accessible from the network you are trying to connect from.
app.use(cors())
before other calls or enable it for specifics routes as oriented here;If you haven’t, consider including error handling based on these guidelines to facilitate the debug process.