2017-08-07 66 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); 
} 
相关问题