尝试访问服务器上启用了CORS的其他域中的Web服务.当我使用Postman测试Web服务时,一切正常,我收到以下响应头:
Access-Control-Allow-Headers:Content-Type Access-Control-Allow-Methods:GET,POST,DELETE,PUT,OPTIONS Access-Control-Allow-Origin:*
当我的Web应用程序(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; }
解决方法
以下错误消息可能会造成混淆:
XMLHttpRequest cannot load http://example.com/mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource.
如果在服务器上未正确设置CORS,则可能会出现此消息,但如果服务器本身以非2XX状态代码(即500)响应,则也会发生此消息.我想,因为这是一个错误,服务器不觉得需要填充适当的CORS启用响应头.当浏览器没有看到这些标题时,它会返回类似CORS的错误.
如果你很好奇,我的Web服务失败的原因是因为我试图将’application / json’数据提交给它不支持的Web服务.一旦我将其切换为使用’application / x-www-form-urlencoded’并稍微修改了角度语法,它就可以正常工作.