angular v5.1.0 HttpClient未设置头内容类型:application / json

时间:2017-12-15 11:19:38

标签: angular httpclient

我正在尝试将post api的标题设置为application.json

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

但没有设定。

10 个答案:

答案 0 :(得分:13)

要使用新的 HttpClient 类定义内容类型,您需要:

  1. @angular/common/http导入(而不是从当前标记为已弃用的@angular/http导入)
  2. import { HttpClient, HttpHeaders } from '@angular/common/http';
    
    1. 在构造函数上注入HttpClient
    2. constructor(private http: HttpClient) { }
      
      1. 定义私有字段headers以定义所需的内容类型,并options来准备您将在通话中使用的对象:
      2. private options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
        
        1. 在您的方法中使用它:
        2. this.http.post('your target url', yourBodyObject, this.options)
          

          其中'your target url'yourBodyObject仅用作示例,需要替换为您的真实数据。

答案 1 :(得分:6)

Angular文档中有一节内容 - 最近可能会添加:

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

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};
当我尝试使用上述格式向httpOptions添加响应类型时,TypeScript给了我警告,所以我成功使用了以下内容:

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

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

文档link

答案 2 :(得分:3)

检查一下,

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

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

用于Http通话。

答案 3 :(得分:2)

在此处尝试此代码=>

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

答案 4 :(得分:1)

以下是一个例子:

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 );
}

我希望这会对你有所帮助。

答案 5 :(得分:0)

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

答案 6 :(得分:0)

OP代码段:

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

定义了 type { headers?: {'Content-Type':'application/json'} }类型的选项变量,该变量是有效的,但不是您想要的变量。将:更改为=以使其成为赋值,并删除了?,这对赋值无效。这是合法的,与OP所尝试的最接近,并且应该起作用:

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

答案 7 :(得分:0)

如果您使用的是http.put(),请使用以下代码并接收json /纯文本:

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);

答案 8 :(得分:0)

这是我在user.service.ts中获取用户详细信息的方式

导入:

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

在类内声明变量:

@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));
    }
  }
}

答案 9 :(得分:0)

我们可以通过创建新的 HttpHeaders 对象来定义请求标头。

HttpHeaders对象本质上是不可变的。因此,请在同一行中设置所有标头详细信息。

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
      });
  }