无法使用角度访问 api

Posted

技术标签:

【中文标题】无法使用角度访问 api【英文标题】:can't access api using angular 【发布时间】:2021-04-29 01:08:12 【问题描述】:

我有一个 API,我需要使用它来创建报告,但是该 API 需要用户名和密码才能访问它,通过使用 curl 命令我可以访问该 API

curl -X GET "https://SomeApiCall/api/v1/customers/" -H "accept:application/json; charset=UTF-8" -u "username:password"

但是当我尝试使用 angular 使用相同的 API 时,我遇到了错误

key:"api.error.invalid_auth_schema"
message: "Invalid authentication scheme is used. Only Basic Authentication scheme is supported (login and password should be provided)"

Angular 示例代码:

 this.data = this.http.get("https://SomeApiCall/api/v1/customers/" , 
      headers: new HttpHeaders(
        'Authorization': 'Basic' + btoa('username:password'),
        'Content-Type':  'application/json'
      )
    );

谁能解释一下,我犯了什么错误?

【问题讨论】:

您在 auth 标头中缺少一个空格。 'Authorization': 'Basic ' + btoa('username:password') @jonrsharpe, Deipirscher:是的,你们俩都是对的,非常感谢 :) 【参考方案1】:

我认为问题在于您在“基本”之后没有空格。改为:

 this.data = this.http.get("https://SomeApiCall/api/v1/customers/" , 
  headers: new HttpHeaders(
    'Authorization': 'Basic ' + btoa('username:password'),
    'Content-Type':  'application/json'
  )
);

【讨论】:

以上是关于无法使用角度访问 api的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 JWT 和 x-www-form-urlencoded 以角度 2 访问 spring API

无法将web api服务数据绑定到角度为2的ng2-smart-table

无法将JSON数据访问到角度(.ts)文件中

带有 mat-select 的角度动态表单无法获取值访问器

无法在无法使用i18n的角度7中进行文件本地化/翻译

为啥在 API 级别 30 上使用范围存储无法访问某些音频文件?