对请求正文的http.put()的错误请求

时间:2018-03-02 15:43:00

标签: angular typescript

我正在使用来自'@ angular / common / http'的HttpClient,并希望执行put操作。

My Angular代码如下:

public updateDetails(data: Data) {


    const url = '/project/rest/v1/configuration/device/update'
    console.log(JSON.stringify(data));
    let headers = new HttpHeaders();
     headers.append('Content-Type' , 'application/json');


    let body = JSON.stringify(data);

    return this.http.put(url, data, { headers: headers })
      .map(response => true)
      .catch(err => {
        console.log(err);
        return Observable.of(false);
      });

  }

但是,我正在

  

HttpErrorResponse {headers:HttpHeaders,status:400,statusText:“Bad   请求”,

请帮助我,我错过了什么。我试图以stringfy格式传递数据,但这也给了我同样的错误。

2 个答案:

答案 0 :(得分:2)

看起来你有两个问题。

  1. headers.append不会修改headers对象,它会返回一个新的header对象,并附加标题。
  2. 所以,而不是

    let headers = new HttpHeaders();
    headers.append('Content-Type' , 'application/json');
    

    你应该做

    const headers = new HttpHeaders()
       .append('Content-Type' , 'application/json');
    
    1. 您不需要对数据进行字符串化 -
    2. 将对象传递给HttpClient, 如:

      this.http.put(url, data, { headers: headers })
      

答案 1 :(得分:0)

尝试

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

return this.http.put(url, data, options)