最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

cors - Angular HttpRequest Interceptor Adding Header Not Working - Stack Overflow

programmeradmin4浏览0评论

Using Angular 14 on Win10. I've built a browser app (running non-SSL via ng serve) for LAN use only, that sends a POST request to a web server running on the same LAN. The web server is a Siemens LOGO PLC, which I cannot alter for CORS. To work around the CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource, I'm trying to intercept the HttpRequest and add the missing header, as shown below. When I break before the return, and inspect corsReq, it does not appear to have Access-Control-Allow-Origin header added. The header map is empty, as shown in the screenshot of my debug session.

Why is the header not being added?

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class CORSInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header.
    const corsReq = req.clone({
      headers: req.headers.set('Access-Control-Allow-Origin', '*'),
    });

    // Send the newly created request
    return next.handle(corsReq);
  }
}

Using Angular 14 on Win10. I've built a browser app (running non-SSL via ng serve) for LAN use only, that sends a POST request to a web server running on the same LAN. The web server is a Siemens LOGO PLC, which I cannot alter for CORS. To work around the CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource, I'm trying to intercept the HttpRequest and add the missing header, as shown below. When I break before the return, and inspect corsReq, it does not appear to have Access-Control-Allow-Origin header added. The header map is empty, as shown in the screenshot of my debug session.

Why is the header not being added?

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class CORSInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header.
    const corsReq = req.clone({
      headers: req.headers.set('Access-Control-Allow-Origin', '*'),
    });

    // Send the newly created request
    return next.handle(corsReq);
  }
}

Share Improve this question asked Mar 18 at 1:47 BobCBobC 3712 gold badges6 silver badges19 bronze badges 1
  • 1 Is your API setting up CORS properly and allowing your origin? If not, then on the preflight check, the API won't give you those headers in the response headers. – 2189490 Commented Mar 18 at 4:28
Add a comment  | 

2 Answers 2

Reset to default 1

Your approach to adding the Access-Control-Allow-Origin header in an Angular HTTP interceptor won't work because:

1. CORS headers are set by the server

  • The Access-Control-Allow-Origin header is a response header, not a request header.
  • The browser enforces CORS policies based on response headers, which means your Angular app cannot override them.

2. Angular Interceptors Modify Requests, Not Browser Policies

  • Even if you add Access-Control-Allow-Origin to the request, the browser ignores it because the server needs to send this header in the response.

  • The preflight request (OPTIONS) is sent before the actual request, and the server must respond with the correct CORS headers.

** Workarounds:**

1. Use a Reverse Proxy (Recommended)

Since you cannot modify the Siemens LOGO PLC server, you can set up a reverse proxy on your machine or another server within your LAN that acts as a bridge. This proxy will add the necessary CORS headers.

  • If using Angular CLI proxy, create a proxy.conf.json file:

    { "/api": { "target": "http://PLC_IP_ADDRESS", "secure": false, "changeOrigin": true, "logLevel": "debug", "headers": { "Access-Control-Allow-Origin": "*" } }}

Then, update your angular.json to use this proxy:

"serve": {
  "options": {
    "proxyConfig": "proxy.conf.json"
  }
}

Start Angular with:

ng serve --proxy-config proxy.conf.json

Now, your frontend can send requests to http://localhost:4200/api, and the proxy will forward them to the PLC.

This header is a response header specifically designed for security to protect the server thus you cannot add it to request headers. If you cannot modify the headers from the server, you will need to either

  1. Run a proxy server along with your application that forwards the requests and adds appropriate headers.
  2. Open the app in a browser with lowered security - making it ignore the headers.
发布评论

评论列表(0)

  1. 暂无评论