CORS Policy Explained: Why It’s Important and How to Fix CORS Errors

Onur Yüksel
5 min readMar 18, 2023

--

Cors Policy Explained: Why It’s Important and How To Fix CORS Errors ?

If you have ever attempted to send a request from the client side, or if you have developed a backend application that provides authentication, you may have encountered at least one of these errors:

Access to XMLHttpRequest at {URL} from origin {origin} has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Access to XMLHttpRequest at {URL} from origin {origin} has been blocked by CORS policy: Blocked by CORS policy.

Access to XMLHttpRequest at {URL} from origin {origin} 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.

Access to XMLHttpRequest at {URL} from origin {origin} has been blocked by CORS policy: Request header field {header-name} is not allowed by Access-Control-Allow-Headers in preflight response.

In this article, we will delve into what CORS is, why it’s crucial for web security, and how to troubleshoot and fix related errors that you may encounter when developing web applications.

What is CORS?

CORS (Cross-Origin Resource Sharing) is an HTTP header-based mechanism that allows servers to permit or block ( using the Same Origin Policy) access to resources such as fonts, scripts, and images on a web page to be shared between different servers.

A website that works on domain-a.com and getting resources from same origin and these are always allowed. But the other side same website trying to getting resources from domain-b.com and this request is controlled by CORS
An example of a CORS request (source: https://developer.mozilla.org/)

How CORS Works?

The CORS mechanism works during the preflight request, which is triggered under the following conditions:

  1. When the HTTP request method is other than GET, HEAD, or POST.
  2. When custom headers are included in the request using the setRequestHeader() method in JavaScript.
  3. When the Content-Type header is not one of the following:
  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

If any of these conditions are met, the browser sends an HTTP request (OPTIONS) to the origin to check if the actual request is allowed. This request includes the Access-Control-Request-Method and Access-Control-Request-Header.

The server responds with headers indicating whether the actual request will be allowed or not. If the server allows the request, the browser sends the actual request. If it’s not allowed, the server returns an error indicating that the request has been blocked by the CORS policy.

Why CORS Is Important?

Without CORS, The Same Origin Policy will restrict sending requests and getting resources from different origins which can be a security feature to prevent cross-site scripting (XSS) and CSRF(XSRF) attacks.

CORS is a Security Feature that allows getting resources from different origins securely by allowing web servers to specify which other domains are allowed to access their resources, and what type of interactions are allowed.

With CORS we can set which origins can get resources from the server by relaxing the Same Origin Policy while still protecting against security vulnerabilities.

How Can I Fix The CORS-Related Errors?

The solutions depend on what you are trying to do. Do you have control over the server side or not?

I DON’T HAVE CONTROL OVER THE SERVER SIDE

CHECK THE CORS MESSAGE

Read the error message carefully. The error message may give you a clue about what is causing the issue.

CHECK THE SERVER’S CORS SETTINGS

Make sure the server you are sending requests to accepts requests from other origins.

USE A PROXY SERVER

If the server doesn’t allow you to send requests from different origins, you can use a proxy server to send requests on behalf of the server.

USE A BROWSER EXTENSION

There are extensions to solve CORS problems, such as CORS Unblock, Moesif Origin & Cors Changer. However, be aware that these extensions don’t provide a permanent solution. You can use these extensions for testing purposes only.

USE A DIFFERENT API

If none of the above can solve the problem, and you don’t have control over the server you are sending requests to, you can consider using a different API.

I HAVE CONTROL OVER THE SERVER SIDE

Ensure that your server correctly handles preflight (OPTIONS) requests and sends appropriate headers. The most common header for allowing other origins is ‘Access-Control-Allow-Origin.’ You can set the header using middleware, or you can create custom logic to set it. When you set ‘Access-Control-Allow-Origin,’ you can specify the origin as an asterisk “*”, which means all domains can send requests to your server. However, it is better to control the allowed origin rather than using an asterisk, which could allow the stealing of your client’s session headers.

In addition to the ‘Access-Control-Allow-Origin’ header, ensure that you have correctly configured the allowed methods and headers by using other headers such as Access-Control-Allow-Methods, Access-Control-Allow-Headers, and Access-Control-Expose-Headers.

Here’s how you can configure your server’s CORS policy with PHP:

// set the allowed origin, method, and headers
header('Access-Control-Allow-Origin: http://yourclientsidedomain.com');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// check if the request is an OPTIONS request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
// set the allowed methods and headers for the preflight request
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
// stop processing the request and return a 200 status code
http_response_code(200);
exit;
}

// continue processing the request as normal
// …

Make sure you are setting the request headers only for the preflight request, which is OPTIONS, and ensure that you do not allow any harmful headers or origins.

It’s important to note that allowing cross-origin requests can introduce security risks to your application. Make sure to use caution when implementing any of the above solutions and only allow cross-origin requests if it is necessary for your application’s functionality.

USEFUL RESOURCES

--

--

Onur Yüksel

Jr Backend Developer @Jotform. Passionate about building scalable apps. Sharing insights on tech, best practices, and experiences. Let's connect!