Comprehensive Analysis and Solutions for Angular 7 CORS Policy Errors

Nov 09, 2025 · Programming · 14 views · 7.8

Keywords: Angular 7 | CORS Policy | Cross-Origin Requests | Proxy Configuration | Backend Configuration

Abstract: This article provides an in-depth analysis of CORS policy errors in Angular 7 projects, explaining browser same-origin policy mechanisms and presenting three effective solutions: backend CORS configuration, Angular proxy setup, and hosts file modification. By comparing differences between Postman and browsers, it helps developers understand the essence of CORS issues with complete code examples and configuration instructions.

Overview of CORS Policy Errors

During Angular 7 development, when making HTTP requests from the local development server http://localhost:4200 to external API endpoints like http://5.160.2.148:8091/api/trainTicketing/city/findAll, developers frequently encounter CORS (Cross-Origin Resource Sharing) policy errors. The error message clearly states: Access to XMLHttpRequest at 'http://5.160.2.148:8091/api/trainTicketing/city/findAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Deep Dive into CORS Mechanism

CORS is a security policy implemented by modern browsers to control cross-origin HTTP requests. When a web application running from one origin (such as http://localhost:4200) attempts to access resources from a different origin, the browser automatically sends a preflight request to check if the target server permits cross-origin access.

The preflight request uses the OPTIONS method and includes the following key headers:

Access-Control-Request-Method: GET
Access-Control-Request-Headers: content-type
Origin: http://localhost:4200

The server must respond with appropriate CORS headers:

Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type

Postman vs Browser Differences

Many developers are confused about why API calls work correctly in Postman but fail in browsers due to CORS errors. The fundamental reason is that Postman, as a desktop application, is not subject to browser same-origin policy restrictions and does not send preflight requests. Browsers, however, strictly enforce CORS policies for security reasons.

Solution 1: Backend CORS Configuration

The most standard solution involves configuring CORS support on the backend server. Below are configuration examples for different backend frameworks:

Spring Boot Configuration Example:

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("http://localhost:4200")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*");
            }
        };
    }
}

Or using annotations at the controller level:

@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class CityController {
    @GetMapping("/api/trainTicketing/city/findAll")
    public List<City> findAllCities() {
        // Business logic implementation
    }
}

.NET Core Configuration Example:

public void ConfigureServices(IServiceCollection services) {
    services.AddCors(options => {
        options.AddPolicy("AllowAngularApp",
            builder => builder
                .WithOrigins("http://localhost:4200")
                .AllowAnyMethod()
                .AllowAnyHeader());
    });
    
    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
    // CORS middleware must be after UseRouting but before UseEndpoints
    app.UseRouting();
    
    app.UseCors("AllowAngularApp");
    
    app.UseAuthorization();
    app.UseEndpoints(endpoints => {
        endpoints.MapControllers();
    });
}

Solution 2: Angular Proxy Configuration

For development environments, Angular CLI provides proxy functionality to avoid CORS issues. Create a proxy.conf.json file:

{
  "/api": {
    "target": "http://5.160.2.148:8091",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

Configure the proxy in angular.json:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "your-app:build",
    "proxyConfig": "proxy.conf.json"
  }
}

Angular service code example:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CityService {
  private apiUrl = '/api/trainTicketing/city/findAll';

  constructor(private http: HttpClient) { }

  getCities(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl);
  }
}

Important Limitation: Proxy functionality only works with the ng serve development server and is not available in ng build production builds.

Solution 3: Hosts File Modification

If the backend server supports wildcard domain configurations (such as *.mydomain.example), CORS issues can be avoided by modifying the hosts file:

Windows Systems: Edit C:\Windows\System32\drivers\etc\hosts

Linux/macOS Systems: Edit /etc/hosts

Add the following entry:

127.0.0.1 local.mydomain.example

Then access http://local.mydomain.example:4200 in the browser instead of http://localhost:4200.

Production Environment Considerations

While using AllowAnyOrigin() and AllowAnyMethod() is acceptable in development environments, strict security policies must be implemented in production:

// Production CORS configuration example
services.AddCors(options => {
    options.AddPolicy("ProductionPolicy",
        builder => builder
            .WithOrigins("https://your-production-domain.com")
            .WithMethods("GET", "POST")
            .WithHeaders("Authorization", "Content-Type")
            .AllowCredentials());
});

Common Issue Troubleshooting

1. Middleware Order Issues: Ensure CORS middleware is positioned correctly in the pipeline, especially when using HTTPS redirection

2. Header Configuration: Verify that Access-Control-Allow-Origin headers accurately match the request origin

3. Credential Support: Configure AllowCredentials() if cookies or authentication information need to be sent

Conclusion

CORS policies are an unavoidable security mechanism in modern web development. Understanding their working principles and mastering corresponding solutions is crucial for Angular developers. During development, Angular proxy provides a convenient solution, while proper backend CORS configuration is key to ensuring secure and stable application operation in production environments. Through the multiple solutions provided in this article, developers can choose the most appropriate method based on specific scenarios to resolve CORS-related issues.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.