How to fix No 'Access-Control-Allow-Origin' header is present on the requested resource
- Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (Firefox)
- No 'Access-Control-Allow-Methods' header is present on the requested resource
- No 'Access-Control-Allow-Headers' header is present on the requested resource
Description
CORS, or cross-origin resource sharing, can be annoying to deal with and fix (even for experienced developers!). Intended to be a security measure implemented by browsers, it can crop up unexpectedly (ex. API calls from localhost to a dev environment). Confusingly, you might try debugging the request in a tool like Postman and not be able to reproduce the error. That's because it is only a browser behavior, not something you'll see in backend service calls to other backend services.
Examples
await fetch('subdomain.example.com'); // maybe error
await fetch('subdomain.example.com', {
method: 'POST',
headers: {
'custom-key': 'value'
}
}); // maybe error
Solution
For CORS issues, the fix must happen on the server - there is no way to opt-out in the client call. When a cross-origin request (example.com -> thirdparty.com, or even foo.example.com -> bar.example.com), the browser will verify that special headers are present in the response and that they match the request. These headers on the response must match the request:
- Access-Control-Allow-Origin - to be the most secure this should match the URL of the requesting page, but you can also use a wildcard "*"
- Access-Control-Allow-Methods - the HTTP method must match the request method (ex. POST)
- Access-Control-Allow-Headers - only some specific headers are allowed by default, any additional headers (ex. client-id) must be explicitly allowed by the server
return {
status: 201,
headers: {
'Access-Control-Allow-Origin: 'www.example.com',
'Access-Control-Allow-Methods: 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers: 'client-id'
}
};
Note: The HTTP method OPTIONS is almost never used except for the purpose of CORS. Browsers will send what is called a "preflight request" with an OPTIONS method before calling the actual GET, POST, or PUT (etc.). The CORS headers above should also be implemented on the OPTIONS version of any endpoints that have CORS issues (even if an OPTIONS endpoint doesn't exist yet).