我正在远程使用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.
预先感谢
答案 0 :(得分:0)
前段时间我也有同样的问题,请参见此处:angular-2-authentication-headers
在标头授权中,您必须已经在其中加密了用户名和密码,如下所示:
headers = headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
并始终确保在后端正确配置了您的CORS策略,由于这个原因,我遇到了多个问题...