【问题标题】:how to pass api key along with the post request如何将 api 密钥与发布请求一起传递
【发布时间】:2021-11-06 20:55:56
【问题描述】:

我正在使用 Angular 并有发布请求,结果出现未经授权的错误。 我还需要传递 api 密钥,这是我的发布请求:

SendToBackEnd(){         
    var x=new mymodel();
    x.settlementCurrency='EUR';
    x.customerReference='m455';
    x.paymentReference='65465465';
    this.http.post("address",x).subscribe(s=>{
    });
}

你能帮我解决这个问题吗?不知道我应该如何将 api 密钥与我的请求一起传递

【问题讨论】:

  • 我说,要么放在地址上,要么放在 x 上。 x.apiKey="mykey"address?apikey=mykey。这将取决于您的后端对它的期望和处理方式。如果不知道后端代码,我们就无法真正分辨。
  • @TheFool 在邮递员它的标题里面,我仍然得到 401 错误
  • 您在邮递员中遇到错误?您有一个 Authorization 标头,例如 Bearer mykey ?
  • @TheFool 在邮递员中工作在角度错误 401 中,在邮递员 api 中,密钥位于标题中
  • 什么样的标题?

标签: angular http-post httprequest


【解决方案1】:

地址在哪里为您的端点提供身份验证参数

var address = 'https://adressToEndpoint.com/?apiKey=key 

  SendToBackEnd(){         
        var x=new mymodel();
        x.settlementCurrency='EUR';
        x.customerReference='m455';
        x.paymentReference='65465465';
        this.http.post("address",x).subscribe(s=>{
        });
      }

【讨论】:

  • 它在邮递员的标题内,我仍然收到错误 401
  • 确保您提供的密钥顺序正确。
【解决方案2】:

这对我有用。我为标题创建了一个函数,所以我可以在任何地方重用它。您可能希望将此函数放在帮助文件中以重复使用它。

  createAuthorizationHeader(headers: Headers) {
    headers.append('Content-Type', 'application/json');
    headers.append('api-key', `xxxxxxxxxxxxxxxxxxxx`);
  }


  SendToBackEnd(){
    const header = new Headers();
    this.createAuthorizationHeader(header);
     
    var x=new mymodel();
    x.settlementCurrency='EUR';
    x.customerReference='m455';
    x.paymentReference='65465465';
    this.http.post("address",x,
    {
      headers: header
     }).subscribe(s=>{
    });
  }

请注意,api-key 应以您的服务器期望的方式命名,例如 apiKey。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-15
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多