繁体   English   中英

Angular 6 Http请求失败,并带有授权标头

[英]Angular 6 Http request fails with authorization headers

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

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;
      }
    });

永恒的工作很好,但是当我添加标题字段时

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服务器,该请求之前已被阻止,不允许角检查响应头

谢谢您的帮助

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

阅读所有评论后,我为您做了一些更改。

更改您的此代码, 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;
      }
    });

您需要在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过滤器''部分下的cors.allowed.methodshttps : cors.allowed.methods

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM