【问题标题】:How to add Basic Authentication header in post request using Angular? [duplicate]如何使用 Angular 在发布请求中添加基本身份验证标头? [复制]
【发布时间】:2021-06-19 03:23:46
【问题描述】:

我有一个执行发布请求的函数,它是这样的,现在在后端我有基本身份验证,这意味着我必须在这个请求中传递标题用户名和密码才能成功调用 api,我尝试了类似的东西这并没有成功..

clickSubmit(event) {
    let httpHeaders = new HttpHeaders();
    httpHeaders.append('Content-Type', 'application/json');
    httpHeaders.append("Authorization", "Basic " + btoa("00000:magical"));

    const httpOptions = {
      headers: httpHeaders
    };

    let user = {
      "userId": this.userId,
      "userName": this.name,
      "adharno": this.adharno,
      "pancardno": this.pancardno,
      "address": this.address,
      "joineddate": this.joinedDate
    }
    const base_URL = 'http://localhost:8090/v1/users'
    return this.http.post(base_URL, user, httpOptions);


  }

【问题讨论】:

    标签: javascript angularjs angular


    【解决方案1】:

    基本身份验证的标头格式为

    Authorization: Basic <credentials>

    其中 是用冒号连接的用户名和密码,然后进行 Base64 编码。

    因此,您使用以下方式创建凭据:

    const credentials = btoa(`${username}:${password}`);

    然后将您的帖子选项设置为

    {headers: new HttpHeaders({Authorization: `Basic ${credentials}`});

    【讨论】:

      猜你喜欢
      • 2019-08-08
      • 2018-07-30
      • 1970-01-01
      • 2021-01-13
      • 2019-12-18
      • 1970-01-01
      • 2019-01-31
      • 2021-11-19
      • 1970-01-01
      相关资源
      最近更新 更多