lmngn23
lmngn23

Reputation: 521

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Reactjs

I'm deploying my web app to heroku and use the following cors config on the client side.

 const instance = axios.default.create({
    baseURL: "https://myapp-backend.herokuapp.com",
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "https://myapp-backend.herokuapp.com"
    }
});

And on the server side

const corsConfig = {
   origin: ['https://myapp.herokuapp.com', 'http://localhost:3001']
}

app.use(cors(corsConfig));

But I keep getting error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Any help would be much appreciated. Sometimes the config works but sometimes it doesn't...

Upvotes: 0

Views: 1887

Answers (1)

jfriend00
jfriend00

Reputation: 708146

The custom headers on your request (some of which are misguided) have triggered a pre-flight request for the cross origin request. This means that the browser will separately send an OPTIONS request to your server to ask it if it is OK to process this request before sending the actual request.

You have a couple of choices. First, remove the custom headers that are triggering the pre-flight request. Neither Content-Type or Access-Control-Allow-Origin are appropriate for a request you are sending from the browser. Content-Type belongs to the response and the client does not get to specify anything about what origins are allowed - that's for the server to decide.

If, for some reason, you can't stop the browser from triggering the pre-flight request, then you need to explicitly add support to your server for the OPTIONS pre-flight request. You can see how to use the cors module to do that here.

Upvotes: 1

Related Questions