Cross-Origin Resource Sharing (CORS) is a security feature implemented in web browsers to prevent malicious scripts from making unauthorized requests on behalf of the user. When a web page makes an AJAX request to a different origin (domain, protocol, or port), the browser sends a preflight OPTIONS request to the server to determine whether the actual request should be allowed.
In this tutorial, we will explore how CORS works and how to add custom headers to AJAX requests using jQuery.
What is CORS?
CORS is a security feature that restricts web pages from making requests to a different origin than the one the web page was loaded from. This prevents malicious scripts from making unauthorized requests on behalf of the user. When a web page makes an AJAX request to a different origin, the browser sends a preflight OPTIONS request to the server to determine whether the actual request should be allowed.
Preflight OPTIONS Request
The preflight OPTIONS request is sent by the browser before the actual AJAX request. This request includes the following headers:
Access-Control-Request-Method
: specifies the HTTP method of the actual requestAccess-Control-Request-Headers
: specifies the custom headers included in the actual request
The server responds to the preflight request with a set of headers that indicate whether the actual request should be allowed. The most important headers are:
Access-Control-Allow-Origin
: specifies which origins are allowed to make requestsAccess-Control-Allow-Methods
: specifies which HTTP methods are allowedAccess-Control-Allow-Headers
: specifies which custom headers are allowed
Adding Custom Headers to AJAX Requests
To add custom headers to an AJAX request using jQuery, you can use the headers
option or the beforeSend
callback.
$.ajax({
type: 'POST',
url: 'https://example.com/api/endpoint',
headers: {
"My-First-Header": "first value",
"My-Second-Header": "second value"
}
});
// or
$.ajax({
type: 'POST',
url: 'https://example.com/api/endpoint',
beforeSend: function(xhr) {
xhr.setRequestHeader("My-First-Header", "first value");
xhr.setRequestHeader("My-Second-Header", "second value");
}
});
However, if the server does not include the custom headers in the Access-Control-Allow-Headers
response header, the browser will not include them in the actual request.
Enabling CORS on the Server
To enable CORS on the server, you need to configure the server to respond with the necessary headers. The exact configuration depends on the server software being used.
For example, in Apache, you can add the following lines to your .htaccess
file:
Header set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "My-First-Header, My-Second-Header, Authorization, content-type, csrf-token"
In Nginx, you can add the following lines to your nginx.conf
file:
location ~ ^/index\.php(/|$) {
...
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'My-First-Header, My-Second-Header, Authorization, Content-Type, Accept, Origin';
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 204;
}
}
By understanding how CORS works and configuring your server to respond with the necessary headers, you can make cross-origin AJAX requests with custom headers.