CORS error: blocked by CORS policy (no Allow-Origin header)
Fix "blocked by CORS policy" when your frontend on localhost calls an API: add the right headers on the server, or use a dev proxy.
CORS is a browser rule: a page from one address (such as localhost:5173) may only read answers from another address (such as localhost:3000) if that server allows it. The fix belongs on the API server, not in your frontend code.
What to do, step by step
- Open the browser console and the Network tab. Read which origin was blocked and which header is missing.
- Add the allow header on the server for your frontend's exact origin, such as http://localhost:5173.
- Check the server also answers the OPTIONS request (the preflight) with status 200 or 204 and the same headers.
- During development you can avoid CORS by proxying API calls through your dev server. See the Vite example below.
- Reload with the cache disabled and test again.
Commands you can copy
npm install cors
const cors = require('cors');
app.use(cors({ origin: 'http://localhost:5173' }));add_header Access-Control-Allow-Origin "http://localhost:5173" always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;export default {
server: {
proxy: { '/api': 'http://localhost:3000' }
}
}Other causes to check
- Wildcard * with credentials
- If you send cookies, the server may not answer Access-Control-Allow-Origin: *. Name the exact origin and add Access-Control-Allow-Credentials: true.
- Preflight fails with 404 or 405
- The server does not handle OPTIONS. Add a handler, or use the cors package, which does it for you.
- Opening the HTML file directly (file://)
- The page origin is null. Serve it from a local server instead, such as npx serve or your dev server.
- It works in Postman but not in the browser
- Postman does not enforce CORS. Only browsers do, so the server must send the headers.
- A custom header is blocked
- List it in Access-Control-Allow-Headers, for example Authorization or Content-Type.
Questions about CORS error on localhost
- Is it safe to allow all origins?
- For a public read-only API it can be fine. For anything with logins, name the exact origins you trust instead of using *.
- Can I fix CORS in my frontend code?
- No. The browser checks the answer headers that the server sends. The only frontend-side option is a proxy that makes the call from your own origin.
- Why does CORS only happen in the browser?
- It is a browser safety feature. Tools like curl and Postman do not enforce it.
Config generators for this
- nginx reverse proxy configSend visitors from port 80 to an app running on port 3000.
- Caddyfile reverse proxySend visitors to an app on port 3000 and get HTTPS certificates automatically.
- nginx rate limit configSlow down abusive visitors with limit_req: a request rate per IP, a burst, and a 429 answer.