How to fix CORS policy error when calling API from FrontEnd.

Tram Ho

What is CORS

CORS is a mechanism that allows many different resources (fonts, Javascript, etc.) of a website to be queried from a domain other than the domain of that site. CORS stands for Cross-origin resource sharing.

What is a CORS policy error

When you call the API to the server without the Access-Control-Allow-Origin header or its value is invalid, this error will generate and no data will be retrieved from the API. Access to XMLHttpRequest at 'API_URL' from origin 'FRONTEND_URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How to fix

The most radical remedy is that the server will configure enable CORS so that the client can call data, you can refer to how to enable with the languages ​​here Enable CORS on Server

In addition to the above, you can manually fix the client to be able to call data, by disabling the security mode on the browser to run (Recommended only for the development process), specifically you can follow the following way:

Run Chrome browser without CORS

On different operating systems, there will be different ways to run, turn on the terminal and paste the following commands corresponding to the browsers

window

OSX

Linux

You will see the following message, select Start Google Chrome to get started

Attention

From Chrome 22+ you will see the following message: You are using an unsupported command-line flag: --disable-web-security. Stability and security will suffer.

Conclude

The article is based on my research process when working in the project encountering CORS policy when calling API of customers, however, it is difficult to ask KH to add CORS config to call from FE side, so I need to handle on the client side during the develop process. Hope to help you meet similar situations ?

Share the news now

Source : Viblo