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:
- Open Network Tab
- Filter by
OPTIONS - Check Response Headers:
Access-Control-Allow-OriginAccess-Control-Allow-MethodsAccess-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
