gpt4 book ai didi

angular - 获取 "No ' Access-Control-Allow-Origin' header is present on the requested resource"错误,即使 CORS 设置正确

转载 作者:太空狗 更新时间:2023-10-29 18:08:14 25 4
gpt4 key购买 nike

尝试在服务器上启用 CORS 的情况下访问不同域中的 Web 服务。当我使用 Postman 测试 Web 服务时,一切正常,我确实收到了以下响应 header :

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

当我尝试访问网络服务的 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;
}

最佳答案

以下错误消息可能令人困惑:

XMLHttpRequest cannot load http://example.com/mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource.

当服务器上的 CORS 设置不正确时,可能会出现此消息,但如果服务器本身以非 2XX 状态代码(即 500)响应,也可能会出现此消息。我想,因为这是一个错误,所以服务器觉得不需要填充适当的支持 CORS 的响应 header 。当浏览器看不到这些 header 时,它会返回类似 CORS 的错误。

如果您好奇的话,我的 Web 服务失败的原因是因为我试图将“application/json”数据提交到它不支持的 Web 服务。一旦我将其切换为使用“application/x-www-form-urlencoded”并稍微修改了 Angular 语法,它就可以正常工作。

关于angular - 获取 "No ' Access-Control-Allow-Origin' header is present on the requested resource"错误,即使 CORS 设置正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45527935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com