2017-08-07 33 views
1

如何在angular2中爲http添加GET請求的用戶名和密碼的標頭?如何爲http設置header使用angular2

我嘗試添加httpclient和http導入無法正常工作。你能告訴我如何在http中添加標題並傳遞我的用戶名和密碼嗎?

+1

的可能的複製[Angular2 - 爲每個請求套頭(https://stackoverflow.com/questions/34464108/angular2-set -headers-for-every-request) – mxr7350

+0

我的問題是如何將用戶名和密碼傳遞給標題 – CodeMan

+0

你知道不能安全地實現這個嗎? –

回答

1

您可以設置這樣的標題:

yourMethodWhereYouPost(userName:string, password:string) 
{ 
    // .... 
    // Your code 
    // 

    // Get the authorization header. 
    const authHeader = this.getAuthorizationHeader(userName, password); 
    const headers = new Headers({ 'Content-Type': 'application/json' }); 
    headers.append('Authorization', authHeader); 
    // .... 

    // Some more code 
} 

private getAuthorizationHeader(userName: string, password: string): string 
{ 
    // Return the encoded auth header. 
    return btoa(userName + ':' + password); 
} 
相關問題