Getting error blocked by cors policy no ‘access-control-allow-origin’ header in angular 18|17|16 application, means you have not set the Access-Control-Allow-Origin property or CORS is not enabled on server response.
Cross-origin resource sharing (CORS) is a security mechanism implemented by browsers to prevent unauthorized access by making requests to a different domain without permission. It helps in securing the web server.
If you use external API in Angular application, and the server response does not have CORS enabled, then at that time, you will get blocked by CORS policy, No ‘Access-Control-Allow-Origin’ header is present on the requested resource in angular. To fix this, simply enable cors on server and it will add the “Access-Control-Allow-Origin” on header with the response.
Here are some steps to fix the error blocked by Cors policy no ‘access-control-allow-origin’ header in angular 18|17|16:
Step 1: Setup Proxy Configuration
Simply navigate to your angular app root directory and open src/proxy.conf.json
file, and then enable proxy configuration by adding the following code into it:
{ "/api/*": { "target": "http://localhost:3000", "secure": false, "logLevel": "debug" } }
After that, open the angular.json
file, and add proxy.conf.json
file into it like the following:
"architect": { "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "project-name:build", "proxyConfig": "src/proxy.conf.json" }, } }
Step 2: Enable Cors in Server
If you are using Express and Node js app for rest apis, simply install cors and enable it response.
To run the following command to install the cors
package in node/express backend:
npm install cors --save
Now open your server.js or index.js and use cors like the following in it:
// server.js const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); /* server configuration here */
Conclusion
Congratulations, you have learned how to fix blocked by cors policy no ‘access-control-allow-origin’ header in angular 18|17|16.