How to correctly set Http Request Header in Angular 2

HttpAngularAngular2 Http

Http Problem Overview


I have an Ionic 2 application using Angular 2, which is sending an Http PUT to a ASP.NET Core API server. Here's the method I'm using to send the request:

public update(student: Student): Promise<Student>
{
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('authentication', `${student.token}`);

    const url = `${this.studentsUrl}`;

    return this.http
        .put(url, JSON.stringify(student), { headers: headers })
        .toPromise()
        .then(() => student)
        .catch(this.handleError);
}

I'm setting an authentication key/value on the headers object.

But when I receive this request on the server, I cannot find the authentication key on the header:

enter image description here

As you can see in the picture, there are many keys on the header, but not the content and authentication keys that I manually added to the header in the client application.

What am I doing wrong?

Http Solutions


Solution 1 - Http

Your parameter for the request options in http.put() should actually be of type RequestOptions. Try something like this:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);

let options = new RequestOptions({ headers: headers });
return this.http
    .put(url, JSON.stringify(student), options)

Solution 2 - Http

Angular 4 >

You can either choose to set the headers manually, or make an HTTP interceptor that automatically sets header(s) every time a request is being made.


Manually

Setting a header:

http
  .post('/api/items/add', body, {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
  })
  .subscribe();

Setting headers:

this.http
.post('api/items/add', body, {
  headers: new HttpHeaders({
    'Authorization': 'my-auth-token',
    'x-header': 'x-value'
  })
}).subscribe()

Local variable (immutable instantiate again)

let headers = new HttpHeaders().set('header-name', 'header-value');
headers = headers.set('header-name-2', 'header-value-2');

this.http
  .post('api/items/add', body, { headers: headers })
  .subscribe()

> The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.

From the Angular docs.


HTTP interceptor

> A major feature of @angular/common/http is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.

From the Angular docs.

Make sure you use @angular/common/http throughout your application. That way your requests will be catched by the interceptor.

Step 1, create the service:

import * as lskeys from './../localstorage.items';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';

@Injectable()
export class HeaderInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (true) { // e.g. if token exists, otherwise use incomming request.
            return next.handle(req.clone({
                setHeaders: {
                    'AuthenticationToken': localStorage.getItem('TOKEN'),
                    'Tenant': localStorage.getItem('TENANT')
                }
            }));
        }
        else {
            return next.handle(req);
        }
    }
}

Step 2, add it to your module:

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HeaderInterceptor,
      multi: true // Add this line when using multiple interceptors.
    },
    // ...
  ]

Useful links:

Solution 3 - Http

> We can do it nicely using Interceptors. You dont have to set > options in all your services neither manage all your error responses, > just define 2 interceptors (one to do something before sending the > request to server and one to do something before sending the server's > response to your service)

  1. Define an AuthInterceptor class to do something before sending the request to the server. You can set the api token (retrieve it from localStorage, see step 4) and other options in this class.

  2. Define an responseInterceptor class to do something before sending the server response to your service (httpClient). You can manage your server response, the most comon use is to check if the user's token is valid (if not clear token from localStorage and redirect to login).

  3. In your app.module import HTTP_INTERCEPTORS from '@angular/common/http'. Then add to your providers the interceptors (AuthInterceptor and responseInterceptor). Doing this your app will consider the interceptors in all our httpClient calls.

  4. At login http response (use http service), save the token at localStorage.

  5. Then use httpClient for all your apirest services.

You can check some good practices on my github proyect here

enter image description here

Solution 4 - Http

For us we used a solution like this:

this.http.get(this.urls.order + '&list', {
        headers: {
            'Cache-Control': 'no-cache',
        }
    }).subscribe((response) => { ...

Reference here

Solution 5 - Http

This should be easily resolved by importing headers from Angular:

import { Http, Headers } from "@angular/http";

Solution 6 - Http

You have a typo.

Change: headers.append('authentication', ${student.token});

To: headers.append('Authentication', student.token);

NOTE the Authentication is capitalized

Solution 7 - Http

The simpler and current approach for adding header to a single request is:

// Step 1

const yourHeader: HttpHeaders = new HttpHeaders({
    Authorization: 'Bearer JWT-token'
});

// POST request

this.http.post(url, body, { headers: yourHeader });

// GET request

this.http.get(url, { headers: yourHeader });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrbasniakView Question on Stackoverflow
Solution 1 - HttpPaul Jerome BordalloView Answer on Stackoverflow
Solution 2 - HttpBrampageView Answer on Stackoverflow
Solution 3 - HttpDaniel DelgadoView Answer on Stackoverflow
Solution 4 - HttpcjohanssonView Answer on Stackoverflow
Solution 5 - HttpIsto BartonView Answer on Stackoverflow
Solution 6 - HttptheCrabView Answer on Stackoverflow
Solution 7 - HttpLeon GrinView Answer on Stackoverflow