简体   繁体   中英

Set response headers from angular http interceptor

I am trying to set a new header on every http response so the response includes a content-security-policy using the latest version of angular. I have created this http interceptor, and when I go to add to the header I don't get any errors or anything, but nothing actually gets added to the response headers. Here is the code I have for the interceptor. Is there anything that I should change here, or is it not possible to add response headers to every http response from angular.

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

@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

      return next.handle(req).pipe(
        filter(event => event instanceof HttpResponse),
        tap((event: HttpResponse<any>) => {
          event.headers.append('content-security-policy', 'some content-security-policy')
        })
      );
      }
    }

You can not alter history: The network tab shows what was sent across the network, and you can not retroactively change that.

What an HttpInterceptor can do is change its own copy of the received headers before passing it on to the subscriber.

Also, a content security header is interpreted by the browser before it passes the response to JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM