🌐 Introduction

If you are using the JavaScript Fetch API to call data from another domain, you might have seen the error: “Cross-Origin Request Blocked” or a CORS error. This error is very common and happens because of the browser’s built-in security rules. Browsers don’t allow websites to make requests to other websites unless the server says it’s okay. This is to protect users from malicious websites.

🚨 What is a CORS Error?

CORS stands for Cross-Origin Resource Sharing.

Example of a CORS error in the browser console

Access to fetch at 'https://api.anotherdomain.com/data' from origin 'https://example.com' has been blocked by CORS policy.

🛠️ 1. Enable CORS on the Server

The best and safest way to fix this issue is to configure the API server to allow cross-origin requests.

Example in Node.js (Express)

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "https://example.com");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

👉 Instead of using * (which allows all domains), it is safer to specify the exact domain like https://example.com.

🌍 2. Use a Proxy Server

Sometimes, you cannot control the API server. In this case, you can use a proxy server.

Example using Node.js as a proxy

// Frontend fetch call
fetch('/proxy/data').then(res => res.json());

// Backend Node.js proxy route
app.get('/proxy/data', (req, res) => {
  fetch('https://api.anotherdomain.com/data')
    .then(apiRes => apiRes.json())
    .then(data => res.json(data));
});

👉 This way, your browser only talks to your own server, so no CORS issues occur.

🧪 3. Use Browser Extensions (For Development Only)

During local development, you can install extensions in Chrome or Firefox that temporarily disable CORS.

🚀 4. Enable CORS in Cloud Services

If your API is hosted on a cloud platform like AWS API Gateway, Firebase, or Azure, you can enable CORS directly in the service settings.

🔄 5. JSONP (Old Method)

Before CORS was introduced, developers used JSONP (JSON with Padding) to bypass restrictions.

💡 Best Practices for Handling CORS

📌 Summary

The “Cross-Origin Request Blocked” error in JavaScript Fetch API happens because browsers stop requests to other domains for safety reasons. The best fix is to enable CORS headers on the server. If you don’t have server access, you can use a proxy server or cloud service settings. For local testing, you can use browser extensions, but this should never be a production solution. By setting up CORS correctly, you make sure your JavaScript applications can securely fetch API data and run smoothly across different environments.