Kinso
Kinso

Reputation: 17

First API request fails because of CORS the following request are successful, REACT.js at the frontend and .NETCORE on the server side

I am making request to a .NetCore API from a React.js client, I have configured the CORS however every time a new device makes a request or if I clear my browser data the first request fails by this error "Access to fetch at '...' from origin '...' has been blocked by CORS policy: No 'Access-Control- Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

The following requests are successful as expected since the configuration has been done on the server side.

        fetch(GET_PAYMENT_URL, {
            method: 'POST',
            mode:'cors',
            headers: {
            'Content-Type': 'application/json',
            },
            body: JSON.stringify(paymentUrlRequest),
        })
        .then((response) => response.json())
        .then((data) => {

        })
        .catch(errorr => {

        });

I expect the first request to be successful on a new device or even if the client clears browser data

Upvotes: 0

Views: 644

Answers (1)

Kinso
Kinso

Reputation: 17

As mentioned by @jub0bs in the comments, the server side is configured to allow listed origins, thus the response header 'Access-Control-Allow-Origin' cannot be static or '*' for all, that's when we use 'Vary': 'Origin' so that the user agent will fetch a response that includes Access-Control-Allow-Origin, rather than using the cached response from the previous non-CORS request that lacks Access-Control-Allow-Origin.

Here is the link CORS protocol and HTTP caches

Upvotes: 0

Related Questions