2016-01-21 24 views
2

我在Angular2 TypeScript中有這個代碼,我嘗試添加如下所示的標頭。Angular2 http.request不能添加標題

['access-token', localStorage.getItem('token')], 
['client', localStorage.getItem('client')], 
['uid', localStorage.getItem('email')], 
['withCredentials', 'true'], 
['Accept', 'application/json'], 
['Content-Type', 'application/json' ] 

發送請求時,我看不到我的請求中的標題。 我正在進行跨域設置。有其他方法可以做到嗎?

private _request(url: string | Request, options?: RequestOptionsArgs) : Observable<Response> { 

    let request:any; 
    let reqOpts = options || {}; 
    let index:any; 

    if(!reqOpts.headers) { 
     reqOpts.headers = new Headers(); 
    } 

    for(index in this._config.authHeaders) { 
     reqOpts.headers.set(this._config.authHeaders[index][0], this._config.authHeaders[index][1]); 
    } 

    request = this.http.request(url, reqOpts); 

    return request; 
} 

這是我的響應頭 enter image description here

+0

您可能需要配置'服務器上的訪問控制允許-Headers'。 –

+0

已經完成,你可以看到我剛剛添加到我的文章的響應標題。當我使用this.http.get時,感謝 – Abhishek

回答

4

如果您的請求是一個跨域之一,所以CORS的概念適用。你可以看看這些鏈接的更多細節:http://restlet.com/blog/2015/12/15/understanding-and-using-cors/http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/。當然,正如Günter所說的那樣,服務器端需要做一些事情來返回CORS頭文件,以便瀏覽器處理響應。

這裏是將報頭在HTTP請求中的示例服務:

我剛纔看到你嘗試設置withCredential

export class MyService { 
    constructor(private http:Http) { 
    } 

    createAuthorizationHeader(headers:Headers) { 
    headers.append('Authorization', 'Basic ' + 
     btoa('a20e6aca-ee83-44bc-8033-b41f3078c2b6:c199f9c8-0548-4be7-9655-7ef7d7bf9d33')); 
    } 

    getCompanies() { 
    var headers = new Headers(); 
    this.createAuthorizationHeader(headers); 

    return this.http.get('https://angular2.apispark.net/v1/companies/', { 
     headers: headers 
    }).map(res => res.json()); 
    } 

編輯。我認爲你混合了不同的東西。 withCredentials不是標準標題,但XHR JavaScript對象上有withCredentials屬性。看到這個鏈接:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials。這應該不使用withCredentials自定義標題。

提醒一下,如果您要使用自定義標題,則需要將其添加到Access-Control-Allow-Headers標題中的服務器端。

希望它可以幫助你, 蒂埃裏

+0

它給我一個錯誤:「預檢響應中的Access-Control-Allow-Headers不允許請求頭部字段withCredentials」。我知道Options方法在CORS中被調用。 http.get嘗試在選項請求 – Abhishek

+0

中設置標題缺少'Access-Control-Allow-Credentials:true' –

+0

剛添加回復標題到帖子 – Abhishek