CORS errors in API requests

Loading

Understanding CORS Errors in API Requests (Cross-Origin Resource Sharing)

Introduction

CORS (Cross-Origin Resource Sharing) is a security feature implemented in web browsers to prevent malicious scripts from making unauthorized requests to different domains. When a frontend application running on one domain attempts to make an API request to another domain without proper CORS headers, the browser blocks the request and throws a CORS error.

This error usually looks like:

Access to fetch at 'https://api.example.com/data' from origin 'https://mywebsite.com' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

Topics Covered in This Guide

  1. What is CORS?
  2. Why Do CORS Errors Occur?
  3. Types of CORS Errors
  4. How to Fix CORS Errors (Client-Side and Server-Side Solutions)
  5. Best Practices to Avoid CORS Issues

1️⃣ What is CORS?

CORS (Cross-Origin Resource Sharing) is a security mechanism that allows or restricts web applications running on different domains from interacting with each other.

  • Same-Origin Policy (SOP): By default, browsers enforce the Same-Origin Policy (SOP), which blocks scripts from making requests to a different domain unless explicitly allowed.
  • CORS Headers: To bypass the SOP, the server must include specific HTTP headers that tell the browser it is safe to share the resources.

Example of a CORS Header

When an API allows cross-origin requests, the response contains:

Access-Control-Allow-Origin: https://example.com

Or, to allow any domain:

Access-Control-Allow-Origin: *

2️⃣ Why Do CORS Errors Occur?

A CORS error occurs when:

  1. The API server does not include the necessary CORS headers.
  2. The API server is blocking requests from certain origins.
  3. The request method (e.g., POST, PUT) is not allowed by CORS policy.
  4. The request includes credentials (cookies, authentication headers) but the server does not allow them.
  5. A preflight request (OPTIONS) fails due to missing headers.

Common Scenarios Where CORS Errors Happen

ScenarioExpected BehaviorCORS Issue
Calling an API from a different domainShould return dataBlocked by browser
Using fetch() or XMLHttpRequest to make a requestShould fetch dataNo CORS headers in response
Requesting resources from a local backend (localhost:3000 to localhost:5000)Should allow accessSame-Origin Policy applies

3️⃣ Types of CORS Errors and How to Identify Them

1. No ‘Access-Control-Allow-Origin’ Header Present

🔴 Error Message

Access to fetch at 'https://api.example.com/data' from origin 'https://mywebsite.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

Fix

  • Ensure the API server includes the Access-Control-Allow-Origin header.
  • Example of how the server should respond:
Access-Control-Allow-Origin: https://mywebsite.com

or

Access-Control-Allow-Origin: *

2. Preflight Request Fails (OPTIONS request)

🔴 Error Message

OPTIONS https://api.example.com/data 405 (Method Not Allowed)

or

Access to fetch at 'https://api.example.com/data' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check.

Fix

  • The API should handle preflight requests (OPTIONS method) by including:
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization

3. Credentialed Requests Blocked (withCredentials: true)

🔴 Error Message

Access to fetch at 'https://api.example.com/data' from origin 'https://mywebsite.com' has been blocked by CORS policy:
The value of the 'Access-Control-Allow-Origin' header must not be '*'.

Fix

  • If your request includes credentials (cookies, authentication tokens), the server must allow them explicitly.
  • The server response should have:
Access-Control-Allow-Origin: https://mywebsite.com
Access-Control-Allow-Credentials: true

4. Redirects Causing CORS Issues

🔴 Error Message

CORS policy: Redirect location 'https://another-api.com' is not allowed.

Fix

  • Make sure the API doesn’t redirect to another domain.
  • If the redirect is necessary, handle it on the server by setting appropriate CORS headers.

4️⃣ How to Fix CORS Errors

Client-Side Fixes

  1. Use a Proxy Server
    • A proxy forwards requests to the API while adding the required CORS headers.
    • Example: Using a proxy in package.json (for React apps):
    "proxy": "https://api.example.com"
  2. Enable CORS in Fetch Requests fetch("https://api.example.com/data", { method: "GET", headers: { "Content-Type": "application/json" }, credentials: "include" })
  3. Use a Browser Extension for Testing

Server-Side Fixes

1. Allow CORS in Express (Node.js)

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors()); // Allows all origins
// OR specify allowed origins
app.use(cors({
    origin: 'https://mywebsite.com',
    methods: 'GET,POST,PUT,DELETE',
    credentials: true
}));

app.get('/data', (req, res) => {
    res.json({ message: "CORS Enabled" });
});

app.listen(5000, () => console.log("Server running"));

2. Allow CORS in Flask (Python)

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Allows all origins

@app.route('/data')
def get_data():
    return {"message": "CORS Enabled"}

app.run()

3. Allow CORS in Nginx

Edit your Nginx configuration:

location /api/ {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
}

5️⃣ Best Practices to Avoid CORS Issues

✅ Always configure the server to allow the correct origins.
✅ Avoid using "*" when sending credentials (use specific domains).
✅ Implement proper preflight request handling (OPTIONS method).
✅ Use reverse proxies to route API requests correctly.
✅ Ensure API redirects do not change the domain.


Final Thoughts

  • CORS errors are a browser security measure, not a bug.
  • The best way to fix CORS errors is to configure the API server properly.
  • If you don’t control the server, use a proxy or enable CORS headers on the client-side requests.

Would you like a specific implementation example for your project (React, Angular, Vue, Node, etc.)?

Leave a Reply

Your email address will not be published. Required fields are marked *