Resolving CORS Policy Blocking XMLHttpRequest Access in Angular Applications

Nov 19, 2025 · Programming · 14 views · 7.8

Keywords: CORS | Angular | Cross-Origin Requests | Preflight Requests | XMLHttpRequest | Access-Control-Allow-Origin

Abstract: This article provides an in-depth analysis of CORS policy blocking PATCH requests in Angular 7 applications, offering both temporary frontend testing solutions and permanent backend configurations. By examining Q&A data and reference articles, it explores CORS preflight mechanisms, Access-Control-Allow-Origin header settings, and best practices for frontend-backend coordination. Complete code examples and step-by-step implementation guides help developers comprehensively resolve cross-origin resource sharing issues.

Problem Background and Error Analysis

During Angular 7 web application development, when attempting to send PATCH requests to servers with different origins, developers frequently encounter CORS (Cross-Origin Resource Sharing) policy blocking XMLHttpRequest access. The typical error message states: "Access to XMLHttpRequest at 'my_url' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status." This indicates that the browser, for security reasons, prevents the execution of cross-origin requests.

In-depth Analysis of CORS Mechanism

CORS is an HTTP header-based mechanism that allows servers to indicate any origins (domain, scheme, or port) other than their own from which browsers should permit loading resources. When a web application attempts to request resources from a domain different from its own, the browser automatically initiates a preflight request—an HTTP request using the OPTIONS method—to determine whether the actual request is safe to send.

The preflight request contains the following key header information:

Access-Control-Request-Method: PATCH
Access-Control-Request-Headers: Content-Type
Origin: http://localhost:4200

The server must respond with appropriate CORS headers for the browser to allow the actual request to proceed. Cases mentioned in reference articles further confirm that even with Access-Control-Allow-Origin headers set, improper configuration of other related headers can still cause CORS errors.

Backend Configuration Issues and Solutions

The provided code example reveals several critical issues in backend configuration:

app.use((req, res, next) => {
    res.set({
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "*",
        "Access-Control-Allow-Headers": "'Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token'",
    });
    next();
});

Main issues include:

The correct backend configuration should be:

app.use((req, res, next) => {
    // Set CORS headers
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
    res.header("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token, Authorization");
    
    // Handle preflight requests
    if (req.method === 'OPTIONS') {
        res.status(200).end();
        return;
    }
    
    next();
});

Frontend Configuration Optimization

Frontend Angular service configuration also requires corresponding adjustments:

patchEntity(ent: any, id) {
    const headers = new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer your-token'  // If using authentication
    });
    
    return this.http.patch(`my_url/${id}`, ent, { headers })
        .pipe(map((res: any) => res));
}

Key improvements:

Temporary Testing Solution

For rapid testing during development, temporarily disabling browser CORS checks can be employed:

In Windows systems, open the Run dialog (Win + R), and enter the following command to launch Chrome:

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

This creates a new Chrome session with web security features disabled, allowing cross-origin requests. Note that this should only be used in development and testing environments, not in production.

Permanent Solution

For production environments, framework-specific CORS configuration is recommended. In Express-based Node.js backends, use the @CrossOrigin annotation:

@CrossOrigin(origins = "*", allowedHeaders = "*")
@PatchMapping("/entities/{id}")
public ResponseEntity<Object> patchEntity(@PathVariable String id, @RequestBody Entity entity) {
    // Business logic processing
    return ResponseEntity.ok(updatedEntity);
}

Or use dedicated CORS middleware:

const cors = require('cors');

app.use(cors({
    origin: 'http://localhost:4200',  // Specify frontend address
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-Auth-Token'],
    credentials: true  // If using cookies or authentication
}));

Preflight Request Handling Mechanism

Understanding the preflight request handling mechanism is crucial for resolving CORS issues. The browser automatically initiates a preflight request when detecting cross-origin requests that meet the following conditions:

The server must correctly respond to OPTIONS requests, returning a 200 status code and appropriate CORS headers, for the browser to proceed with sending the actual PATCH request.

Common Issue Troubleshooting

Based on experiences from reference articles, here are common CORS troubleshooting steps:

  1. Verify the server correctly responds to OPTIONS requests
  2. Check if Access-Control-Allow-Origin headers are properly set
  3. Confirm Access-Control-Allow-Methods includes actually used methods
  4. Ensure Access-Control-Allow-Headers includes all custom headers
  5. Check response status codes—preflight requests must return 2xx status codes
  6. Validate frontend request headers comply with CORS requirements

Security Considerations and Best Practices

In production environments, avoid using wildcard "*" as the value for Access-Control-Allow-Origin, as this poses security risks. Recommended practices include:

Through the above analysis and solutions, developers can systematically resolve CORS issues in Angular applications, ensuring smooth collaboration between frontend and backend components.

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.