Fix the issue- origin ‘http://localhost:4200’ has been blocked by CORS policy in Angular

This article will show how to fix the issue “origin ‘http://localhost:4200’ has been blocked by CORS policy” in Angular.

When working with Angular applications, you may encounter the “Origin ‘http://localhost:4200’ has been blocked by CORS policy” error when attempting to access a cross-domain backend API.

This tutorial provides three solutions to address this issue.

Solution 1: Change the Backend API to Accept Requests from http://localhost:4200

Depending on the backend language or framework, you can configure it to accept requests from the Angular application’s origin (i.e., http://localhost:4200).

For Java Spring Boot API

This section provides a code snippet for Java Spring Boot API, demonstrating how to use the @CrossOrigin annotation in the controller class to allow requests from the specified origin.

@CrossOrigin(origins = "http://localhost:4200")
public class MyCustomController {

    @GetMapping("/custom-endpoint")
    public String customEndpoint() {
        return "Response from custom endpoint";
    }
}

This code snippet is for a Java Spring Boot API. It uses the @CrossOrigin annotation on the controller class (MyCustomController) to explicitly allow requests from the specified origin (http://localhost:4200).

The customEndpoint method represents a sample endpoint that will now accept requests from the Angular application.

For C# or Dotnet Core API (Program.cs or Startup.cs)

Similarly, this section presents code for C# or Dotnet Core API, showcasing how to configure CORS policies in the service collection using AddCors and UseCors methods.

services.AddCors(options =>
{
    options.AddPolicy("AllowAngularOrigins",
        builder =>
        {
            builder.WithOrigins("http://localhost:4200")
                .AllowAnyHeader()
                .AllowAnyMethod();
        });
});

// UseCors
var app = builder.Build();
app.UseCors("AllowAngularOrigins");

For C# or Dotnet Core API, this code is typically placed in the Startup.cs file. It configures CORS in the service collection by defining a policy named “AllowAngularOrigins” that allows requests from the specified origin (http://localhost:4200) with any headers and methods.

The UseCors method is then used to apply this policy to the application.

For Node.js API

Here, the code snippet demonstrates installing and using the cors module to handle CORS in a Node.js API.

const cors = require('cors');
app.use(cors());

For a Node.js API, this code snippet utilizes the cors module. It is added as middleware to the application using app.use(cors()), which allows cross-origin requests by setting the appropriate headers.

For Nestjs applications

For Nestjs applications, the tutorial provides code using the enableCors method to allow cross-origin requests.

app.enableCors({ origin: "http://localhost:4200" });

In Nestjs applications, the enableCors method is used to enable Cross-Origin Resource Sharing.

Here, it is configured to allow requests from the specified origin (http://localhost:4200).

Solution 2: Using Alias Domain

If your backend API accepts requests from wildcard domains like *.domain.com, add an alias name for localhost in your host file.

  1. Open your host file (e.g., /etc/hosts on Unix-based systems, C:\Windows\System32\drivers\etc\hosts on Windows).
  2. Add the following line: 127.0.0.1 angular.domain.example.
  3. In your browser, replace localhost:4200 with angular.domain.example:4200.

Solution 3: Proxying to a Backend Server

If your backend server runs on a different domain and you want to avoid CORS issues during development, use Angular CLI’s proxying feature.

Create a file named proxy-config.json in the src/ folder of your Angular project.

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

In this code snippet, a proxy-config.json file is created in the src/ folder of the Angular project. It defines a proxy configuration for requests with the path /api to be redirected to the backend server at http://localhost:3000. The secure: false option disables SSL certificate validation.

In your angular.json file, add the proxyConfig option to the serve target under architect.

"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy-config.json"
    },
    // ...
  }
  // ...
}

This modification in angular.json integrates the proxy configuration during development (ng serve). It instructs Angular CLI to use the proxy settings specified in proxy-config.json when serving the application.

Run the Angular development server

Run the Angular development server using the ng serve command.

ng serve

The final instruction is to run the Angular development server with the configured proxy settings by using the ng serve command.

This allows the proxy to redirect requests to the specified backend server during development, mitigating CORS issues.

Note: This proxy configuration is applicable only during development (ng serve) and does not affect production builds (ng build).

By following one of these solutions, you can effectively resolve the CORS policy error and enable seamless communication between your Angular application and the backend API.

Leave a Comment

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

Scroll to Top