【问题标题】:Angular 6 Http request fails with authorization headersAngular 6 Http 请求因授权标头而失败
【发布时间】:2018-12-03 03:37:51
【问题描述】:

当我尝试执行此 http 请求时,我正在部署和 angular 6 应用程序,该应用程序与 localhost 中的 tomcat 服务器一起工作

this.http
      .post<LoginResult>( API_URL + '/login', JSON.stringify(json)/*, { headers: myHeader }*/).pipe(
        catchError(this.handleError('get-token', []))).subscribe((response) => {
      if(response['result_code'] == 'result_ok') {
        this.auth.doSignIn(response['token'], response['name']);
        this.router.navigate(['user_manager']);
        return true;
      }else {
        return false;
      }
    });

everitying 效果很好,但是当我添加标题字段时

let myHeader = new HttpHeaders().append("Authorization", 'Basic' + this.session.getAccessToken());

    this.http
      .post<LoginResult>( API_URL + '/login', JSON.stringify(json), { headers: myHeader }).pipe(
        catchError(this.handleError('get-token', []))).subscribe((response) => {
      if(response['result_code'] == 'result_ok') {
        this.auth.doSignIn(response['token'], response['name']);
        this.router.navigate(['user_manager']);
        return true;
      }else {
        return false;
      }
    });

这是我的输出错误:

Access to XMLHttpRequest at 'http://localhost:8095/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
HttpErrorResponse

我还检查了请求没有到达我的 tomcat 服务器,它之前被阻止,不允许角度检查响应头

感谢您的帮助

【问题讨论】:

  • 两件事:不需要JSON.stringify 你的payload,因为Angular会为你做这件事。只需传递实际对象。此外,Basic 和令牌值之间没有空格。
  • 谢谢,但没有解决我的问题

标签: javascript node.js angular typescript tomcat


【解决方案1】:

我为您提供了一个通用的答案,因为您没有提到您的服务器端代码是用哪种语言编写的。
您应该提供服务器代码的标头。提供Access-Control-Allow-Origin 标头,其值为localhost:4200,这将解决您的问题。或者,如果您想允许每个来源,请将其值从 localhost:4200 更改为 *

读完所有的cmets后,我为你改变了一些东西。

将您的此代码 let myHeader = new HttpHeaders().append("Authorization", 'Basic' + this.session.getAccessToken()); 更改为 const myHeader = new HttpHeaders({'Authorization': 'Bearer ' + localStorage.getItem('api_token')}); 并将您的发布请求设为

this.http
      .post<LoginResult>( API_URL + '/login', json, myHeader).pipe(
        catchError(this.handleError('get-token', []))).subscribe((response) => {
      if(response['result_code'] == 'result_ok') {
        this.auth.doSignIn(response['token'], response['name']);
        this.router.navigate(['user_manager']);
        return true;
      }else {
        return false;
      }
    });

【讨论】:

    【解决方案2】:

    您需要在您的 tomcat 服务器上配置 CORS。

    您需要告诉 tomcat 允许应用程序发送哪些标头,以便它可以将其包含在预检响应中:

    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Authorization,Content-Type,...</param-value>
    </init-param>
    

    看看

    cors.allowed.methods 在此处的 CORS 过滤器部分下: https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html

    【讨论】:

    • 你能帮我解决一下我必须写这些行的地方吗?
    • 嗯,我没用过tomcat,但是你需要找到配置文件,你的操作系统是什么?
    • 我用的是windows
    • 你知道tomcat的安装目录吗?如果是,那么 TOMCAT-HOME/conf/server.xmlTOMCAT-HOME/conf/web.xml 应该是配置文件。您可能需要同时搜索cors.allowed.methods
    • 是的,我必须把它放在 web.xml 上?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2018-05-04
    • 1970-01-01
    • 2019-01-10
    • 2011-03-18
    • 1970-01-01
    相关资源
    最近更新 更多