2017-10-19 62 views
0
return this.http.post(this.url + '/' + endpoint, body, {headers: { 
     'customHeader1': 'changed', 
     'customHeader2': 'changed2'  
    }}); 

上面的代碼片段是我的http請求。我可以在沒有標題對象的情況下進行調用,但是我調用的端點在我設置這些標題之前不會返回數據。添加這些標頭會導致應用程序返回以下錯誤:離子頭無法通過http.post設置

user.ts:50 ERROR TypeError: req.headers.forEach is not a function 

如何解決此問題並在http請求中設置我的標頭?

這是我進口

import { HttpClient, HttpParams } from '@angular/common/http'; 
import { Injectable } from '@angular/core'; 
import { Http, Response, RequestOptionsArgs, RequestMethod, Headers, Request 
} from '@angular/http'; 

這是我的構造

constructor(public http: HttpClient) {} 

回答

1

我通常會創建一個選項的 '頭'

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

對象,然後用它

this.http.post(this.url + '/' + endpoint, body, options) 

如在此處所述:https://www.concretepage.com/angular-2/angular-2-http-post-example

+0

修復了我收到的錯誤,但標頭未在請求中設置 – user3044394