1
votes

I have a Angular (version 8) application which is going to redirect / call an external url (not API) with HEADERS.

I am able to call / redirect the external url but not able to send any HEADERS.

The thing is once I am able to LOGIN successfully, I have to send the Authentication token in header to the external url while redirecting.

Please let me know how can I send auth token while redirecting to external url.

I have gone through the below url which helps me to redirect to external url but headers are not getting sent.

Angular 6 Redirect to external url using POST

2

2 Answers

0
votes
  1. You create the headers.

e.g: JSW, if you have your token in localStorage, as "current_user" token:

import { HttpHeaders } from '@angular/common/http';
....
const headers = new HttpHeaders()
  .append("Authorization", "Bearer " + localStorage.getItem("current_user")["token"])
  .append("Content-type", "application/json");
  1. You define your httpOptions.

    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', Authorization: 'your-auth-token' }) };

or more tidy (if you already have declared the const headers before

const httpOptions = {
  headers
};
  1. You make your redirect / call to the external url.
    const externalUrl = 'http://....';
    const dataToPut = 'Usually, it will be an object, not a string';
    
    this.http.post<Hero>(this.externalUrl, dataToPut , httpOptions)
        .pipe(
          catchError(this.handleError('post error: ', dataToPut ))
        );

Anyway, once you know how to do it, the best way to send the Authentication token in header is throught an INTERCEPTOR, that is going to intercept all your http calls and insert in the headers the Authentication parameters: https://angular.io/guide/http#intercepting-requests-and-responses

P.S: I strongly recommend you to read this 2 official documentation pages for further examination... is all there, a more detailed information

https://angular.io/guide/http

https://angular.io/guide/http#adding-headers

[Angular] [http] [headers] [interceptor]

0
votes

I think the way you'd do it is to send the headers through an XHR request. Then if you wanted to reload afterwards you could. But the header transmission would happen first

this.http
.post('api/login', body, {
  headers: new HttpHeaders({
    'Authorization': 'my-auth-token',
    'x-header': 'x-value'
  })
}).subscribe(() => window.location.href='https://some-other-website.com')