How add meta element in HTTP header via req.clone in Angular

Viewed 29

Currently I am cloning request to add some parameter like this:

    const modifiedReq = req.clone(
      { 
        params: new HttpParams().set('MYPARAM', MyParamValue),
      })

Now, to the same request I want to add this in header section:

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

How can I add this?

Update:

I am aware of setting header just like this example:

request = request.clone({
setHeaders: 
{
    Authorization: `Bearer ${token}`
}
});        

This way 'Content-Type' etc can be set. But in my example above, there is something meta is set inside which there are paremeters http-equiv and content which I don't know how to set.

(Additional info: This I am adding in header to allow to mix secure & non-secure requests)

1 Answers

The clone method allows you to pass new or modified headers.

Try this code:

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

import {environment} from '../../../../environments/environment';

export class SetHeaderInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const headers = new HttpHeaders({
      'Authorization': 'token 123',
      'WEB-API-key': environment.webApiKey,
      'Content-Type': 'application/json'
    });


    const cloneReq = req.clone({headers});

    return next.handle(cloneReq);
  }
}

Piece of code taken from this thread : Interceptor Angular 4.3 - Set multiple headers on the cloned request

Related