尝试在服务器上启用CORS的情况下访问其他域中的Web服务。当我使用Postman测试Web服务时,一切正常,我收到以下响应标题:
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, DELETE, PUT, OPTIONS
Access-Control-Allow-Origin:*
当我的网络应用程序(Angular 2)尝试POST到它时,我得到:
XMLHttpRequest cannot load http://example.com/mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource.
我不确定为什么Postman似乎正在接收正确的变量设置,但我的浏览器仍然阻止我使用它。
根据Chrome调试器,预检响应似乎运行良好:
Request Method:OPTIONS
Status Code:200 OK
当我尝试访问Web服务的GET部分时,一切正常:
getJob(id: number): Observable<Job> {
let myParams = new URLSearchParams();
myParams.append('id', id + "");
let options = new RequestOptions({ headers: this.getHeaders(), params: myParams});
return this.http
.get(this.jobsUrl, options)
.map(res => res.json().data as Job)
.catch(this.handleError);
}
这是Web服务的POST部分失败:
createJob(job: Job): Observable<any> {
let options = new RequestOptions({ headers: this.getHeaders()});
return this.http
.post(this.jobsUrl, job, options)
.map(res => res.json().jobID)
.catch(this.handleError);
}
这是getHeaders():
private getHeaders() {
let headers = new Headers();
headers.append('Content-Type','application/json');
return headers;
}
答案 0 :(得分:4)
以下错误消息可能会造成混淆:
XMLHttpRequest cannot load http://example.com/mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource.
如果在服务器上未正确设置CORS,则可能会发生此消息,但如果服务器本身以非2XX状态代码(即500)响应,则也会发生此消息。我想,因为它是一个错误,服务器并不觉得需要填充适当的CORS启用响应头。当浏览器没有看到这些标题时,它会返回类似CORS的错误。
如果您感到好奇,我的网络服务失败的原因是因为我试图提交&#39; application / json&#39;数据到它不支持的Web服务。一旦我将其切换为使用&#39; application / x-www-form-urlencoded&#39;并稍微修改了角度语法,它工作正常。
答案 1 :(得分:3)
查看this article以获取有关CORS的详细说明。
Get和Post之间的区别在于Post应该有一个额外的Content-Type标头。我没有看到你在代码中设置标题,我也不知道Angular或浏览器是否会为你设置它。
我的观点是它与内容类型标题有关,要么它没有在服务器上配置为Access-Control-Request-Headers,要么您需要从客户端代码中明确设置它。