Angular HttpRequest Interceptor Adding Header Not Working

Discussão em 'Angular' iniciado por BobC, Março 17, 2025.

  1. BobC

    BobC Guest

    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);
    }
    }


    [​IMG]

    Continue reading...

Compartilhe esta Página