Getting 'Cross-Origin Request Blocked' on a GET request
Problem
Summary I'm making a GET request to 4chan's API for retrieving threads from a board. This is my code: [code block] I receive the following warning: `Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://a.4cdn.org/a/threads.json. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). ` As seen above, I have added the relevant header, but it does not solve the issue. I made the same request from my terminal using cURL and it worked fine. Context - axios version: e.g.: v0.16.0 - Environment: e.g.: node v6.9.4, Firefox 51.0.1, Ubuntu 14.04
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Implement CORS Proxy for 4chan API Requests
The error occurs because the browser enforces the Same Origin Policy, which restricts web pages from making requests to a different domain than the one that served the web page. The 4chan API does not include the necessary CORS headers ('Access-Control-Allow-Origin') in its response, preventing your frontend application from accessing the data directly.
Awaiting Verification
Be the first to verify this fix
- 1
Set Up a CORS Proxy
Use a CORS proxy to forward your requests to the 4chan API. This proxy will add the necessary CORS headers to the response, allowing your frontend application to access the data.
javascriptconst express = require('express'); const request = require('request'); const app = express(); const PORT = process.env.PORT || 3000; app.use('/proxy', (req, res) => { const url = 'https://a.4cdn.org' + req.url; req.pipe(request({ uri: url })).pipe(res); }); app.listen(PORT, () => { console.log(`CORS Proxy running on port ${PORT}`); }); - 2
Update Frontend API Call
Change your frontend code to make requests to the CORS proxy instead of directly to the 4chan API. This will ensure that your requests include the necessary CORS headers.
javascriptaxios.get('http://localhost:3000/proxy/a/threads.json') .then(response => { console.log(response.data); }) .catch(error => { console.error('Error fetching data:', error); }); - 3
Test the Proxy Setup
Run your CORS proxy server and test the updated frontend code to ensure that you can successfully retrieve data from the 4chan API without CORS issues.
bashnode cors-proxy.js - 4
Deploy the CORS Proxy
If the proxy works locally, consider deploying it to a cloud service (like Heroku or AWS) to make it accessible from your frontend application in production.
bashheroku create my-cors-proxy git push heroku main
Validation
Confirm that the CORS proxy is running and that your frontend application can successfully make requests to the proxy endpoint without encountering CORS errors. Check the browser console for any errors and ensure that the expected data is logged.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep