While developing the Octagon API project, I encountered an issue related to the API, which was deployed as a microservice on Cloudflare Workers.
From Node.js, there was no issue fetching data from multiple endpoints. However, when attempting to fetch this data from a browser, the following error occurs:
Access to fetch at 'https://api.octagon-api.com/rankings' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Let’s see how to solve it!
Fixing the CORS Error"undefined" anchor link
- Go to you Cloudflare dashboard and select your domain.
- Now, in the side menu, expand the “Rules” dropdown menu and click on “Transform rules”.
- In the tabs menu, click on “Modify Response Header” and then on “Create rule”.
- A form will appear. Fill it out as follows:
- Rule Name: Enter a descriptive name for the rule.
- If incoming requests match…: Select Custom Filter Expression.
- In the condition section:
- Field: Choose URI Full.
- Operator: Select Wildcard.
- Value: Enter the URL pattern to capture requests directed to this API. In my case:
https://api.octagon-api.com/*
.
- In the Then… dropdown, select Add:
- Header Name:
access-control-allow-origin
- Value:
*
- Header Name:
- Click Save to apply the rule.
Now, your API will allow requests for data from any origin, and the CORS error should no longer appear!
I hope you found this article useful.
Happy coding! 🚀