【问题标题】:Angular httpClient get response using authorization Bearer Unknown ErrorAngular httpClient 使用授权承载未知错误获取响应
【发布时间】:2021-08-24 22:15:15
【问题描述】:

服务.ts

public welcome(token: any){
    let tokenString = "Bearer "+token
    console.log("tokenString is: "+tokenString)
    let header = new  HttpHeaders().set("Authorization",tokenString);
    const requestOptions = {  headers: header};  
    return this.httpClient.get('http://localhost:8191/api/',{
      responseType: 'text' as 'json',
      headers: header
    });
  }

网页控制台:

tokenString 是:承载 eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqYXZhdGVjaGllIiwiZXhwIjoxNjIzMTMyNzc5LCJpYXQiOjE2MjMwOTY3Nzl9.h6aw8VBFHXWJQ5R2jRyn0MUqbe4rT3RvUCsELfcKHSU

从源“http://localhost:8191/api/”访问 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} 消息:“http://localhost:8191/api/ 的 Http 失败响应:0 未知错误” 名称:“HttpErrorResponse” 好的:假的 状态:0 statusText:“未知错误” 网址:“http://localhost:8191/api/”

Controller Postman 请求正在运行 enter image description here

【问题讨论】:

  • 查看消息,问题是由于CORS,服务器不接受请求。您需要在您的服务器上enable CORS 或通过另一台服务器代理请求。
  • 该信息无关紧要。在http://localhost:8191/api/ 运行的 API/服务器,您是否在该 API/服务器上启用了 CORS?
  • 我已经添加了 @CrossOrigin(origins = "*") 并且我实际上调用了我发送凭据以接收令牌的控制器,因为我在控制台中看到了 tokenString输出。我试图听取您的建议,并在方法调用上方添加了 @CrossOrigin(origins="localhost:4200/") 但我仍然看到相同的错误 Angular CLI: 11.2.9; Node: 14.16.1; OS: win32 x64; Angular: 11.2.10 对不起,我无法编辑它

标签: node.js angular typescript jwt cross-origin-read-blocking


【解决方案1】:

要解决 CORS 问题,您有两种方法 1. 在您的服务器上启用 CORS 或 2. 通过创建一个名为 proxy.conf.json 的文件来代理您的请求,如下所示:

{
"/api": {
  "target": "http://localhost:8191/",
  "changeOrigin": true
}

}

然后像这样调用 this.httpClient.get('/api/',...)

【讨论】:

  • 你好,我也试过了,它的接缝显示相同的想法,所以不要改变什么
  • 以上配置将url改写为localhost:4200/api...,应该可以解决问题。对于borwser,就好像您访问的是同一个源。您是否在 angular.json 中包含了 proxy.conf.json?检查这个答案stackoverflow.com/questions/47536466/…
猜你喜欢
  • 1970-01-01
  • 2018-12-20
  • 2016-10-31
  • 1970-01-01
  • 2019-11-24
  • 1970-01-01
  • 1970-01-01
  • 2018-09-05
  • 2023-03-27
相关资源
最近更新 更多