Search code examples
javascriptnode.jsreactjsherokupreflight

CORS policy issue on Heroku Server


I made a client-server application. The backend uses Node, Express and MongoDB Atlas.

I already installed CORS and used it as a middleware like:

const cors = require('cors')

app.use(cors())

Then I deployed it to heroku which returned an endpoint; like : https://express-server.herokuapp.com

I used that endpoint in my client which is based on React.

I use axios to make a request to the server such as:

const response = await axios.post('https://express-server.herokuapp.com/users/login' ,{some data here})

This is where the error occurs. Every time I make a request the following response pops up in the console.

enter image description here

What is the solution for this????


Solution

  • You have to define in your server from which origin requests should be accepted

    Assuming your localhost runs on port 3000. Try this code

    app.use(
        cors({
            origin: "http://localhost:3000", 
            credentials: true,
        })
    );
    

    NOTE: credentials true is set to pass HTTP only cookies