【发布时间】:2018-01-13 15:21:16
【问题描述】:
尝试访问不同域中的 Web 服务,并在服务器上启用了 CORS。当我使用 Postman 测试 Web 服务时,一切正常,我确实收到了以下响应标头:
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, DELETE, PUT, OPTIONS
Access-Control-Allow-Origin:*
当我的 Web 应用程序 (Angular 2) 尝试向其发布时,我得到:
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
当我尝试访问网络服务的 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);
}
失败的是网络服务的 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;
}
【问题讨论】:
标签: angular web-services cors