Loading

CORS (Cross-Origin Resource Sharing) Errors

Asked by Shaykot Hossain Selim Β· Β· 7 answers

CORS errors occur when a web app on one domain tries to access resources from another domain without proper permissions. Browsers block these requests for security, causing issues in API calls, especially during development or across services.

7 answers

Answered by Shaykot Hossain Selim Β·

Testing & Debugging CORS

🧰 Browser DevTools:

  1. Open Network Tab
  2. Filter by OPTIONS
  3. Check Response Headers:
  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers

πŸ”§ Online Tool:

  • Test CORS Headers
  • [curl Test](command line):
curl -H "Origin: <http://localhost:3000>" --verbose <https://api.example.com>

Answered by Dipa Saha Β·

CORS Configuration in Other Backends

πŸ”§ Laravel (PHP):

// In `app/Http/Middleware/HandleCors.php`
return $next($request)
    ->header('Access-Control-Allow-Origin', '*');

πŸ”§ Flask (Python):

from flask_cors import CORS
app = Flask(__name__)
CORS(app, origins=["<http://localhost:3000>"])

πŸ”§ ASP.NET Core:

app.UseCors(policy =>
    policy.WithOrigins("<http://localhost:3000>")
    .AllowAnyMethod()
    .AllowAnyHeader());

Answered by Md Sharifuzzaman Shajib Β·

How to Fix CORS in Express.js (Node.js)

πŸ”§ Use CORS Middleware:

npm install cors

πŸ”§ Code:

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

app.use(cors({ origin: '<http://localhost:3000>' })); // Allow specific origin
// or
// app.use(cors()); // Allow all origins (not recommended in production)

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

Answered by Fozle Rabbi Β·

When to Use Credentials with CORS

πŸ”§ Enable Credentials:

Frontend:

fetch('<https://api.example.com/data>', {
  credentials: 'include'
});

Backend:

res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Origin', '<https://your-frontend.com>');

πŸ”΄ Note: You cannot use "*" as the origin when credentials: true.

Answered by Mynul Islam Β·

Fixing CORS in Frontend Only (Development)

When the backend is not modifiable (e.g., third-party API), use proxying.

πŸ”§ Option 1: Vite/React Proxy

// vite.config.js
server: {
  proxy: {
    '/api': '<https://external-api.com>',
  }
}

πŸ”§ Option 2: Next.js

// next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: '<https://external-api.com/:path*>',
      },
    ]
  },
}

Answered by Sahin Khan Β·

Setting wildcard * with credentials

❌ Browsers block this if credentials: true is set

βœ… Use specific origin(s) instead of * when sending cookies or auth headers

Missing OPTIONS handler for preflight requests

❌ Requests like PUT, DELETE, or custom headers trigger a preflight

βœ… Add a route or middleware to handle OPTIONS with proper CORS headers

Incorrect protocol or domain in origin

❌ http://localhost:3000 β‰  https://localhost:3000

βœ… Make sure Origin in request matches the exact domain and protocol allowed by the server

Allowing all origins (*) in production

❌ Serious security riskβ€”any domain can access your API

βœ… Always specify trusted domains explicitly in production

Not exposing custom headers

❌ APIs sending custom headers may be blocked

βœ… Use Access-Control-Expose-Headers to whitelist headers like X-Total-Count

Setting CORS headers only on GET

❌ Other methods like POST, PATCH will fail

βœ… Apply headers on all relevant routes, including preflight

Hardcoding development origins in production config

❌ Exposes dev origins publicly

βœ… Use environment variables to control allowed origins by environment

Improper Access-Control-Allow-Methods

❌ Omitting needed methods causes request failure

βœ… Explicitly allow GET, POST, PUT, DELETE, OPTIONS, etc.

Not returning CORS headers on failed responses

❌ Browser still checks CORS on 400/500 responses

βœ… Return the same headers even on errors

Answered by Ratul Sikder Β·

CORS Cheatsheet Summary

Access-Control-Allow-Origin

➀ Specifies which origin(s) are allowed to access the resource

Access-Control-Allow-Methods

➀ Defines allowed HTTP methods (e.g., GET, POST, PUT, DELETE)

Access-Control-Allow-Headers

➀ Lists custom headers that can be sent with the request

Access-Control-Allow-Credentials

➀ Enables sending cookies or authorization headers with requests

Access-Control-Max-Age

➀ Sets how long (in seconds) the preflight response can be cached by the browser

Browse more questions from the manob.ai community