Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly set Http Request Header in Angular 2

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?

like image 874
rbasniak Avatar asked Dec 14 '16 02:12

rbasniak


People also ask

How do you pass headers in Angular HTTP?

There are two ways by which we can add the headers. One, we add the HTTP Headers while making a request. The second way is to use the HTTP interceptor to intercept all the Requests and add the Headers. In both cases, we use the httpHeaders configuration option provided by angular HttpClient to add the headers.

How do I add a header to my HTTP request?

To add custom headers to an HTTP request object, use the AddHeader() method. You can use this method multiple times to add multiple headers. For example: oRequest = RequestBuilder:Build('GET', oURI) :AddHeader('MyCustomHeaderName','MyCustomHeaderValue') :AddHeader('MySecondHeader','MySecondHeaderValue') :Request.

Why do we use HTTP headers in Angular?

Http headers is need to authenticate the request, if you have token in your header and the backend will verify your API to check if you are authenticate to get the Response.


2 Answers

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) 
like image 130
Paul Jerome Bordallo Avatar answered Sep 24 '22 07:09

Paul Jerome Bordallo


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:

  • Interceptor not working properly.
  • APP_INITIALIZER not working in combination with interceptor
like image 37
Brampage Avatar answered Sep 21 '22 07:09

Brampage