API calls blocked by CORS even with Access-Control-Allow-Origin : * present in headers

Issue

API calls from react site keep getting blocked by CORS even tho both the react app and the api are served with Access-Control-Allow-Origin : * header along with allowed methods 'GET,PUT,POST,DELETE,OPTIONS' and cors credentials are allowed as well

This is the exact error :

Access to XMLHttpRequest at 'https://cbiapi.dailycode.tk/parse/classes/_Installation' from origin 'https://backoffice.dailycode.tk' 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.

website URL : https://backoffice.dailycode.tk/login
API url : https://cbiapi.dailycode.tk/parse

I don’t understand why my api calls are still blocked, I tried CORS everywhere plugin and other plugins of the kind but calls are still being blocked

Solution

Your client request (based on what’s in the request) has triggered a cross origin pre-flight check. That means the browser will send your client an OPTIONS request (to the same URL of the request) and it expects to get back a 2xx status in order to allow the CORS request.

Any number of things can trigger a pre-flight request. These include most custom headers, and many content-types other than just a couple.

You can see more in this other answer and you can read about it on MDN here.

Your API server will need to handle an OPTIONS request. You don’t show any of the relevant API server code, but if the URL is https://cbiapi.dailycode.tk/parse and the server environment was Express, you would need something like this in your API server:

app.options("/parse", cors(), (req, res) => {
    res.sendStatus(204);
});

This can be adjusted to only allow some origins if you want it partially locked down. This example would allow all origins to do cross origin access from a browser.

Answered By – jfriend00

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.