Angular Cors Policy no ‘access-control-allow-origin’

Angular Cors Policy no ‘access-control-allow-origin’

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.

Recommended Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *