简体   繁体   中英

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.

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.

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

Check this,

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

and

let headers = new Headers({ 'Content-Type': 'application/json'});     
let options = new RequestOptions({headers: headers});

for Http call.

在这里试试这段代码=>

let header = {'Content-Type':'application/json'}

Here is an example:

public _funName( _params ): Observable<void> {
    const headers = new Headers( { 'Content-Type': 'application/json' }  // set your header);
    /* The option withCredentials: true in the code bellow is used with the CORS variables, that is when the REST functions are on another server then Node.js and the Angular2 development application. */

    const options = new RequestOptions( { headers: headers, withCredentials: true } );

    return this.http.post( _yourLink, _params, options )
    .map( this.extractData )
    .catch( this.handleError );
}



public extractData( res: Response ) {
    const body = res.json();
    // const body = res;
    return body || {};
}

public handleError( error: Response | any ) {
    let errMsg: string;
    if ( error instanceof Response ) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify( body );
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error( errMsg );
    return Observable.throw( errMsg );
}

I hope this will help you.

let hdr = {
        'Content-Type': 'application/json'
    };
let options = { headers: hdr };
this.httpClient.post(url, payloadData, options);

The OP code snippet:

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

is defining an options variable of type { headers?: {'Content-Type':'application/json'} } , which is valid but not what you want. Change the : to a = to make it an assignment , and removed the ? , which is not valid for assignments. This is legal, closest to what the OP was attempting, and should work:

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

If you are using http.put() then use following code and receiving json/plain text:

const httpOpt = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Accept': 'application/json, text/plain'
  })
};

this.http.put('http://localhost:8080/bookapi/api/book/'+id, JSON.stringify(requestObj), httpOpt);

This is how I get user details inside user.service.ts

Imports:

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs/Observable'; 
import {Injectable} from '@angular/core';

Declaring variables inside class:

@Injectable()
export class UserService {

private httpHeaders = new HttpHeaders().set('Content-Type','application/json');
protected options = {headers: this.httpHeaders,
    search:{}
};

constructor(private http: HttpClient) {

    }

/**
 * getting user details
 * @returns {Observable<any>}
 */
getUser(): Observable<any>{
    return this.http.get('userApi/').catch(err => this.errorHandler(err));
}

/**
 *
 * @param error
 * @returns {any}
 */
errorHandler(error: any): any {
    if (error.status < 400) {
        return Observable.throw(new Error(error.status));
    }
  }
}

We can define the Request headers by creating new HttpHeaders object.

HttpHeaders object is immutable by nature. So set the all the header details in the same line.

getUser(name: string, age: string) {
    const params = new HttpParams().set('name', name).set('age', age);

    const headers = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Authorization', 'my token');

    return this.http
      .get(`${endPoint}/user`, {
        params,
        headers
      });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM