1

FULL ERROR

Access to fetch at 'http://localhost:5000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set

I have this error when I try to make request in reactjs, but I don't have problems with curl for example.

Curl request

I have also tried with "Access-Control-Allow-Origin: *"

OmbraOscura
  • 11
  • 1
  • 4
  • Does this answer your question? [No 'Access-Control-Allow-Origin' - Node / Apache Port Issue](https://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue) – Đăng Khoa Đinh Jun 11 '21 at 20:00

2 Answers2

2

This is due to the CORS policy on your Node server, as both the client and server are running on different ports they are considered different "origins". CORS is a mechanism that indicates the origin that is allowed access to resources on the server. This is useful to stop unwanted requests to an API from unknown origins and more information can be found on MDN.

An option is set the CORS origin from within your server. If you're using Express, you can use middleware the set the origin:

app.use(cors({
    origin: 'http://localhost:3000/'
}))

Or, if you'd rather do it manually:

app.use(() => (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();
});

It's important to note that when you deploy your application this origin will need to be updated to match the host address, be that a static IP or domain. Therefore it would be useful to set this as an environment variable.

Additionally, you can set a proxy within your React package.json like so: "proxy": "http://localhost:5000/" however this does not work in production.

0

I interpret this as you're running react webserver on port 3000 and a node backend listening on 5000.

you can't make requests cross origin (from the domain localhost:3000 to the domain localhost:5000) because of the cors policy.

The header Access-Control-Allow-Origin: * should be set by the node backend, but this is a very bad solution. you should add a proxy key to ypur react package json which will proxy all your requests to another server. (see https://create-react-app.dev/docs/proxying-api-requests-in-development/)