【问题标题】:how to set authorisation header with username & password in angular4如何在angular4中使用用户名和密码设置授权标头
【发布时间】:2019-03-20 11:04:57
【问题描述】:

我正在远程使用 Java Rest API 服务。他们正在发送用户名和密码以及授权服务。在这里,我使用的是 angular6,我传递的标题有问题。下面是我的代码

import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders} from '@angular/common/http';
import { Http, Response } from '@angular/http';
import { Observable, Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { HttpModule } from '@angular/http';
`
@Injectable()

export class MasterService{

constructor(private http:HttpClient) { }

getApi(url): Observable<any> {
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append("Authorization", "Basic YWRtaW46YWRtaW4=");
headers = headers.append('Access-Control-Allow-Origin', '*');
headers = headers.append('UserName', 'admin');
headers = headers.append('password', 'admin');
return this.http.get(url,{ headers:headers })
  .map((res) => {
    console.log(res);
    return res;
}).catch(this.handleErrorObservable);
}
}
`

我遇到了这样的错误

OPTIONS http://publicIp/coms/getEnterpriseCutomerDtls?custid=10 401 
(Unauthorized)

Access to XMLHttpRequest at 'http://publicIp/coms/getEnterpriseCutomerDtls? 
custid=10' from origin 'http://localhost:4200' has been blocked by 
CORSpolicy: Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource.

提前致谢

【问题讨论】:

  • 也许你必须在服务器上启用 CORS...
  • 返回错误消息是有原因的。如果你用谷歌搜索它的通用部分(即所有不是特定于你的环境的东西,比如省略端点),你会发现很多关于 CORS 的链接。从那里开始。

标签: angular


【解决方案1】:

前段时间我也有同样的问题,请看这里:angular-2-authentication-headers

在您的标头授权中,您必须拥有已加密的用户名和密码,如下所示:

headers = headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));

并始终确保您的 CORS 策略在您的后端正确配置,因此我遇到了几个问题...

【讨论】:

  • 您好,感谢您的回复。我已经尝试过该行,但无法正常工作。刚才我通过链接发现OPTION请求有问题。我将此消息转发给我的后端团队。我认为它可能会帮助我摆脱这个问题。谢谢和问候
猜你喜欢
  • 2015-06-16
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
相关资源
最近更新 更多