Getting an error blocked by cors policy no ‘access-control-allow-origin’ header in the angular application means you have not set the Access-Control-Allow-Origin property OR CORS is not enabled on the server response.
Here are steps to fix the error blocked by Cors policy no ‘access-control-allow-origin’ header in angular:
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.