2016-03-03 71 views
4

我試圖從Angular2公測後第8 JSON,但頭部沒有被傳輸:打字稿/ Angular2 http.post不設置頭

import { RequestOptions, RequestMethod, RequestHeaders, RequestOptionsArgs, Http } from 'angular2/http'; 

// ... 
let headers = new Headers(), 
    body = JSON.stringify({ identifier, password }); 

headers.append('Content-Type', 'application/json'); 
headers.append('Accept', 'application/json'); 
let opts:RequestOptionsArgs = { headers: headers }; 

this.http.post(this.baseUrl + 'auth/login', body, opts) 
    .subscribe(
     data => console.log(data), 
     err => console.log(err.json().message), 
     () => console.log('Authentication Complete') 
    ); 

但在Chrome瀏覽器中調用XHR不有這些標題中的任何一個。 Chrome調試顯示Content-Type標頭標記爲Provisional Headers are Shown並顯示Content-Type:text/plain;charset=UTF-8。頭值似乎是正確的,但:

console.log(headers.get('Content-Type')) // => 'application/json' 
console.log(headers.get('Accept'))  // => 'application/json' 

的問題是,我在拉RequestHeaders,但它應該只是Headers。爲什麼它沒有給我一個錯誤,我不知道。

+0

你能檢查這個帖子嗎?可能它可以解決你的問題。 [Angular2如何通過發送憑據來獲取令牌](http://stackoverflow.com/questions/35442569/angular2-how-to-get-token-by-sending-credentials) – utnas

+0

閱讀這個asnwer使用'Header' http ://stackoverflow.com/a/34758630/5043867 –

回答

13

您需要導入Headers類這樣的(你忘了你的進口來自angular2/http):

import { 
    RequestOptions, 
    RequestMethod, 
    RequestHeaders, 
    RequestOptionsArgs, 
    Http, 
    Headers // <------ 
} from 'angular2/http'; 

// ... 
let headers = new Headers(), 
body = JSON.stringify({ identifier, password }); 

詳情請參見這個問題: