首页 > 解决方案 > 无法在 Angular http 请求标头中发送用户名和密码

问题描述

我需要在 HTTP 请求中将用户名和密码作为请求标头(不是查询参数)发送。

get在 Angular 服务中编写了以下方法。

 http.get() {
    let headers_object = new HttpHeaders();
    headers_object.append('username', 'Test');
    headers_object.append('password', 'Test123');

    const httpOptions = {
        headers: headers_object
    };
    const uri = 'http://localhost:8083/test';
    let res;
    this.http.get(uri, httpOptions)
    .pipe(map(data => data)).subscribe(result => {
        console.log(result);
        res = result;
    });
    return res;
}

Chrome DevTools 中网络选项卡的屏幕截图

在这个方向上的任何帮助将不胜感激。

谢谢!

标签: angularangular7

解决方案


由于HttpHeaders不可变的(下面不可变对象的定义:),

不可变对象是其状态在创建后无法修改的对象。-什么是可变和不可变数据结构?

这意味着您只能在同一实例中设置一次。

请参阅下面的示例:

let headers_object = new HttpHeaders()
  .set('username', 'Test')
  .set('password', 'Test123');

推荐阅读