Header Ads

Seeing “blocked by CORS policy” in your browser console? This guide shows how to fix CORS errors in Node.js (Express), Angular and Ionic apps, including Capacitor on Android and iOS, with working code for every step.

Seeing “blocked by CORS policy” in your browser console? This guide shows how to fix CORS errors in Node.js (Express), Angular and Ionic apps, including Capacitor on Android and iOS, with working code for every step.

You build an API in Node.js, call it from your Angular or Ionic app, and the browser shows this:

Access to XMLHttpRequest at 'http://localhost:3000/api/ping' from origin
'http://localhost:8100' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.

The same request works fine in Postman, which confuses a lot of developers. This post explains why that happens and walks through the fixes, from the simplest to the production-ready setup.


What Is CORS, and Why Does Postman Work?

CORS (Cross-Origin Resource Sharing) is a rule enforced by the browser, not by your server. An origin is the combination of scheme, host and port. These are all different origins:

  • http://localhost:8100 (ionic serve)
  • http://localhost:4200 (ng serve)
  • http://localhost:3000 (your Node.js API)

When your frontend calls an API on a different origin, the browser only lets your code read the response if the server sends back the right Access-Control-Allow-* headers. Postman and curl are not browsers, so they never enforce this rule. That is why “it works in Postman” tells you the API is fine and the headers are missing.

Why Ionic apps hit this often

Inside a Capacitor app, the web view runs on its own origin, so your API sees a different Origin header in each environment:

Where the app runsTypical origin
Ionic dev server (ionic serve)http://localhost:8100
Angular dev server (ng serve)http://localhost:4200
Capacitor on Androidhttp://localhost
Capacitor on iOScapacitor://localhost
Production web appyour own domain, for example https://app.example.com

Check the exact value in your browser’s DevTools (Network tab, request headers) instead of guessing, because your project settings may differ.


Step 1: Add the cors Middleware in Express

Install the package:

npm install cors

Then allow only the origins you actually use:

const express = require('express');
const cors = require('cors');
const app = express();
const allowedOrigins = [
'http://localhost:8100', // ionic serve
'http://localhost:4200', // ng serve
'http://localhost', // Capacitor Android
'capacitor://localhost', // Capacitor iOS
'https://app.example.com' // production web app
];
app.use(cors({
origin(origin, callback) {
// No Origin header means curl, Postman or server-to-server calls
if (!origin || allowedOrigins.includes(origin)) {
return callback(null, true);
}
return callback(null, false);
},
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 600 // browser may cache the preflight for 10 minutes
}));
app.use(express.json());
app.get('/api/ping', (req, res) => {
res.json({ ok: true });
});
app.listen(3000, () => console.log('API running on port 3000'));

Important: register app.use(cors(...)) before your routes. If it comes after, your routes respond first and the headers are never added.


Step 2: Understand the Preflight (OPTIONS) Request

For requests that send JSON, an Authorization header, or methods like PUT and DELETE, the browser first sends an automatic OPTIONS request called a preflight. It asks the server, “Am I allowed to send this request?” If the preflight does not return the right headers with a success status, the real request is never sent.

The cors middleware answers preflight requests for you when it is registered globally, as in Step 1. If you set headers by hand, you must handle OPTIONS yourself (see Step 4).


Step 3: Fix Credentials (Cookies and Auth)

If your app sends cookies, you need two things to match on both sides:

Server (already set in Step 1):

credentials: true

Angular client:

this.http.get('http://localhost:3000/api/profile', {
withCredentials: true
});

With credentials enabled, the server cannot answer with Access-Control-Allow-Origin: *. It must return the exact requesting origin, which the allow-list in Step 1 does.


Step 4: Set the Headers Manually (No Package)

If you prefer not to use the package, this middleware does the same job:

app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Vary', 'Origin');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
}
if (req.method === 'OPTIONS') {
return res.sendStatus(204); // answer the preflight
}
next();
});

The Vary: Origin header stops caches and CDNs from serving one origin’s response to another.


Step 5: Use the Angular Dev Proxy (Development Only)

During development you can avoid CORS entirely by letting the dev server forward API calls, so the browser sees a same-origin request. Create proxy.conf.json in your project root:

{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true
}
}

Reference it in angular.json:

"serve": {
"options": {
"proxyConfig": "proxy.conf.json"
}
}

Then call a relative URL from your code:

this.http.get('/api/ping');

Restart the dev server after changing the proxy file. This only helps in development. A deployed app still needs the real fix from Step 1 or Step 6.


Step 6: Fix CORS Behind Nginx

The most common production mistake is setting CORS headers in both Node.js and Nginx. The browser then sees duplicates and fails with an error like “The ‘Access-Control-Allow-Origin’ header contains multiple values”. Pick one place.

Option A, let Node.js handle it and have Nginx only proxy:

location /api/ {
proxy_pass http://127.0.0.1:3000;
}

Option B, let Nginx handle it and remove CORS from Node.js:

location /api/ {
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin "https://app.example.com" always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;
add_header Access-Control-Max-Age 600;
return 204;
}
add_header Access-Control-Allow-Origin "https://app.example.com" always;
proxy_pass http://127.0.0.1:3000;
}

The always flag makes Nginx add the header even on error responses such as 401 or 500, which prevents a misleading CORS error hiding the real problem. Reload with sudo nginx -t && sudo systemctl reload nginx.


Step 7: Capacitor Native Apps

On Android and iOS you can either allow the Capacitor origins from the table above, or route requests through the native HTTP layer so the web view’s CORS rules do not apply. In capacitor.config.ts:

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'my-app',
webDir: 'www',
plugins: {
CapacitorHttp: {
enabled: true
}
}
};
export default config;

Run npx cap sync afterwards. Test file uploads and cookie-based logins after enabling this, because native requests behave slightly differently from browser requests.


Common Mistakes Checklist

MistakeFix
Trailing slash in the allowed origin (http://localhost:8100/)Origins have no trailing slash
http vs https, or the wrong portMatch scheme, host and port exactly
cors() registered after the routesMove it above all routes
Custom header like Authorization not allowedAdd it to allowedHeaders
* origin together with credentialsReturn the exact origin instead
API crashes with a 500 before sending headersCheck server logs, since the CORS error can be a symptom
Redirect (301/302) on the preflight requestCall the final URL directly
Headers set in both Nginx and Node.jsSet them in only one place


How to Debug It in 2 Minutes

  1. Open DevTools, go to the Network tab and click the failed request.
  2. Look for the OPTIONS request first. Check that its status is 200 or 204 and that it includes Access-Control-Allow-Origin.
  3. Compare the request’s Origin header with your allow-list, character by character.
  4. Reproduce the preflight from the terminal:
curl -i -X OPTIONS http://localhost:3000/api/ping \
-H "Origin: http://localhost:8100" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: authorization"

If the response has no Access-Control-Allow-Origin header, the problem is on the server side and not in your Angular code.


Security Notes

  • Avoid origin: '*' for APIs that use cookies or sensitive data. Use an allow-list.
  • Never fix CORS by disabling browser security flags. That only hides the problem on your own machine.
  • CORS is not authentication. Your API still needs proper token or session checks.


Conclusion

A CORS error means the browser did not get permission headers from your server. Add the cors middleware before your routes, allow the exact origins your Angular and Ionic app uses (including the Capacitor ones), handle the preflight request, and keep the headers in one place when you deploy behind Nginx. Use the dev proxy only while developing.

Related Guides

Post a Comment

0 Comments