Angular - Can't set new HTTP Header

Viewed 75

I'm trying to add an Authorization token to my request, but the header never get sent to the API,

enter image description here

    public getIndicators(params: Object): Observable<any> {
        const data = {params : params};
        let headers = new HttpHeaders();
        headers = headers.set('testHeader', 'test').set('test2', 'test3').set('Authorization', ' Bearer token');

        return this.http.post(API_URL + '/dashboard/getIndicators', data, {headers: headers});
    }

The same post request works on Postman if I put the headers in so I thought it could be because the app is served on localhost, so I added

    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Allow-Headers "*"

in my apache2 conf and with this simple requests that do not require an Auth header does work

    public login(formUsername: string, formPassword): Observable<any> {
    const data = {
      impersonate: formUsername,
      fmboPassword: formPassword
    };

    return this.httpClient.post<any>(API_URL + '/user/superlogin', data, { observe: 'response' });
  }

Edit: A bit of clarification on the project architecture

I'm running the angular app on my localhost:4200 and got my PHP (CodeIgniter ) api on a docker container (image php:7.2-apache) on port 80, I don't know what could block it.

This is the apache2 conf I set in my Dockerfile

<VirtualHost *:80>

DocumentRoot "/var/www/html/"

ErrorLog "/var/log/apache2/sales-error.log"
CustomLog "/var/log/apache2/sales-access.log" common

<Directory "/var/www/html/">
    AllowOverride All
    Options FollowSymLinks
    Require all granted

    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Allow-Headers "*"

</Directory>
1 Answers

Following should do the trick.

return this.httpClient.post<any>(API_URL + '/user/superlogin', data, { observe: response', headers: new HttpHeaders({'token': 'hello1 ' });

If you want this headers to be sent to server for each BE request you should use HttpInterceptor. https://angular.io/api/common/http/HttpInterceptor

Related