Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular v5.1.0 HttpClient not set header content-type : application/json

I am trying to set header for post api as application.json

let options: { headers?: {'Content-Type':'application/json'} }

but not set.

like image 512
Sopan Zinjurde Avatar asked Dec 15 '17 11:12

Sopan Zinjurde


Video Answer


2 Answers

To define the content-type with the new HttpClient class you need to:

  1. Import from @angular/common/http (and NOT from @angular/http which is currently marked as deprecated)
import { HttpClient, HttpHeaders } from '@angular/common/http';
  1. Inject the HttpClient on the constructor:
constructor(private http: HttpClient) { }
  1. Define a private fields headers to define the content-type desired and options to prepare the object you will use on the call:
private options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
  1. Use it inside your method:
this.http.post('your target url', yourBodyObject, this.options)

where 'your target url' and yourBodyObject are used only as example and need to be replaced with your real data.

like image 121
Luca Ritossa Avatar answered Oct 18 '22 07:10

Luca Ritossa


There is a section on this in the Angular Documentation - probably added quite recently:

import { HttpHeaders } from '@angular/common/http';

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

TypeScript was giving me warnings when I tried to add a response type to httpOptions using the above format, so I use the following successfully:

let headers = new HttpHeaders({
            'Content-Type': 'application/text'
        });

return this.http.get(url, { responseType: 'text', headers })

Docs link

like image 7
Drenai Avatar answered Oct 18 '22 06:10

Drenai