【发布时间】: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