【发布时间】:2018-09-26 18:49:15
【问题描述】:
我正在尝试通过设置了跨域相关标头的 Angular 服务访问 Web 服务。但是,我仍然无法访问网络服务。浏览器一直在说,
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.
我可以在浏览器 (chrome) 和邮递员中访问相同的 URL,但不能在 Angular 应用程序中访问。
private headers = new HttpHeaders()
.set('Access-Control-Allow-Origin', '*')
.set('Content-Type', 'application/json;charset=UTF-8')
.set('Access-Control-Allow-Headers', '*')
.set('Access-Control-Allow-Methods', 'GET, OPTIONS');
public getData(): Promise<Object> {
return this._http.get(this._url, {headers: this.headers})
.toPromise()
.then(response => {
return response;
}
)
.catch(testService.handleError);
}
这里有什么我遗漏的吗...
【问题讨论】:
-
我们可以看看
this._url的值吗? -
发布的代码是为请求资源的客户端,还是为服务器?发送响应时需要设置 CORS 标头的是服务器,而不是请求中的客户端。
-
如果我的想法不错,您正在尝试访问在您的本地主机上运行的 Web 服务。为此,您必须在 Web 服务中允许 CORS,而不是在 Angular 中。该错误表明您尝试访问的服务器(或 Web 服务)未授权您请求他。服务器这样做是出于某种安全原因。如果您想了解更多信息,请查看谷歌上的 CORS 错误。
-
对不起,我的页面没有刷新,CRice回答了你的问题
-
好的。谢谢@CRice 和弥敦道。发布的代码用于从服务器请求资源。
标签: javascript angular web-services cross-browser cross-domain