-1

I'm creating a project with react and node, which consists of an app that adds people data to a database, in this project there is a basic front-end made with react, which is running on localhost:3000 and a back-end made with node that is running on localhost:3333.

The problem is that when I use axios in the font-end to interact (create, get or delete people from the database) with the back-end, at the click of a button, the following error appears:

Access to XMLHttpRequest at 'http://localhost:3333/person/' 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.

This is my code:

const AddPerson = () => {
    const data = axios.post('http://localhost:3333/person/', {
        name: name,
        age: age,
        profession: profession
    })
    console.log(data)
}

1 Answers1

1

You need to allow CORS (cross origin resource sharing) on your server. It's not an axios problem. By default a server rejects requests that don't come from the same IP, this includes the port. Because your frontend and backend run on different ports, it looks to the backend like a "foreign" service trying to request it. This behavior is blocked by default for security reasons.

It'll depend on what your backend is, but I'll assume Vanilla Node, Next or Express

Vanilla node https://bigcodenerd.org/enable-cors-node-js-without-express/

Next https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors

Express https://expressjs.com/en/resources/middleware/cors.html

Michael Brenndoerfer
  • 3,483
  • 2
  • 39
  • 50