我正在尝试从 FireFox 中的不同域向 REST Web 服务发送 POST 请求。我为此使用 JavaScript“获取”函数。我在 IIS 中托管 REST Web 服务。在我在 JavaScript 中添加“Content-Type”标头之前它工作正常。
FireFox 控制台中的 CORS 错误
请注意,如果我在控制台中启用 XHR,那么我可以看到使用带有“Content-Type”的 fetch 会产生 OPTIONS 请求。但是,不使用“Content-Type”会导致 POST 请求。因此 fetch 会触发预检请求,如文档所述。这些是错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com/Service.svc/Request. (Reason: CORS preflight response did not succeed).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com/Service.svc/Request. (Reason: CORS request did not succeed).
TypeError: NetworkError when attempting to fetch resource.
JavaScript 出现 CORS 错误
var body = '{ID:2, Name:"test reqx"}';
var url = "http://example.com/Service.svc/Request";
var init = {credentials:"include", method:"POST", headers:{"Content-Type":"application/json","Accept":"application/json"}, body:body};
fetch(url,init)
.then(response => response.text())
.then(data => console.log(data));
JavaScript 没有 CORS 错误,但也没有 Content-Type
var body = '{ID:2, Name:"test reqx"}';
var url = "http://example.com/Service.svc/Request";
var init = {credentials:"include", method:"POST", headers:{"Accept":"application/json"}, body:body};
fetch(url,init)
.then(response => response.text())
.then(data => console.log(data));
我正在使用“凭据:”包括“”,因为 REST Web 服务配置了基本身份验证。
REST Web 服务 web.config(注意不同的域)
我添加了一些 CORS 配置,以使其他请求在 FireFox 中跨域工作。但是,我找不到允许 Content-Type 的正确配置:
<configuration>
...
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://example.net" />
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST"/>
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
</customHeaders>
</httpProtocol>
...
</system.webServer>
...
</configuration>
如果没有“Content-Type”标头“application/json”,REST Web 服务将无法工作。我该如何解决这些错误?
边注
使用 HTTP 而不是 HTTPS,使示例更容易(因为不需要证书),但它也会以纯文本形式发送基本身份验证的凭据