将 fetch 与 Content-Type 一起使用时出现 CORS 错误 [英] CORS error when using fetch with Content-Type

查看:23
本文介绍了将 fetch 与 Content-Type 一起使用时出现 CORS 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 FireFox 中的不同域向 REST Web 服务发送 POST 请求.我正在使用 JavaScript获取";为此发挥作用.我在 IIS 中托管 REST Web 服务.在我添加内容类型"之前它工作正常JavaScript 中的标头.

i'm trying to send a POST request to a REST web service from a different domain in FireFox. i'm using the JavaScript "fetch" function for this. i'm hosting the REST web service in IIS. it works fine before i add a "Content-Type" header in JavaScript.

FireFox 控制台中的 CORS 错误

请注意,如果我在控制台中启用 XHR,那么我可以看到将 fetch 与Content-Type"一起使用.产生一个 OPTIONS 请求.但是,不使用Content-Type";导致 POST 请求.如文档所述,因此 fetch 正在触发预检请求.这些是错误:

note that if i enable XHR in the console, then i can see that using fetch with the "Content-Type" results in an OPTIONS request. but, not using the "Content-Type" results in a POST request. so fetch is triggering a preflight request as the documentation says. these are the errors:

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.

出现 CORS 错误的 JavaScript

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 服务配置了基本身份验证.

i'm using 'credentials:"include"' because the REST web service is configured with Basic Authentication.

REST Web 服务 web.config(注意不同的域)

我添加了一些 CORS 配置,以使其他请求在 FireFox 中跨域工作.但是,我找不到允许 Content-Type 的正确配置:

i've added some CORS configurations, to make other requests work cross domain in FireFox. but, i can't find the right configuration to allow 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",REST Web 服务将无法工作.标头应用程序/json".我该如何解决这些错误?

the REST web service does not work without the "Content-Type" header "application/json". how can i resolve these errors?

旁注

使用 HTTP 而不是 HTTPS,使示例更容易(因为不需要证书),但它也以纯文本形式发送基本身份验证的凭据

using HTTP instead of HTTPS, makes the examples easier (because no certificates needed), but it also sends the credentials for Basic Authentication in plain text

推荐答案

在 Daniel A. White 提到的问题中,选择的答案是解决方案,尽管略有修改.如何向 WCF 服务添加跨域支持.

the selected answer, in the question referred to by Daniel A. White, was the solution although slightly modified. How to add cross domain support to WCF service.

旁注

当 OPTIONS 调用尚未修复时,我注意到对它的不同响应:

i noticed different responses to the OPTIONS call when it's not yet fixed:

  • 405 方法不允许:在 IIS 中使用匿名身份验证
  • 401 未经授权:在 IIS 中使用基本身份验证但正如丹尼尔指出的那样,两种情况下的 CORS 错误都是相同的

这就是我修改 WCF REST Web 服务并消除 CORS 错误的方式:

this is how i modified the WCF REST Web Service and got rid of the CORS errors:

Global.asax.cs

我还将 Global.asax.cs 文件添加到 Web 服务中.但我没有写在那里添加任何标题,因为它似乎推翻了 web.config.所以决定将其削减到最低限度:

i also added the Global.asax.cs file to the web service. but i did not write add any heaaders in there as it seems to overrule the web.config. so decided to shave it down to the bare minimum:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // prevent 401 unauthorized response to CORS preflight check
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.End();
        }
    }

Web.config

我也将其减少到最低限度(确保您已 runAllManagedModulesForAllRequests=true")

i shaved this down to the bare minimum as well (make sure you have runAllManagedModulesForAllRequests="true")

<configuration>
  ...
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    ...
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://example.net" />
        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Allow-Headers" value="Content-Type"/>
      </customHeaders>
    </httpProtocol>
    ...
  </system.webServer>
  ...
</configuration>

这篇关于将 fetch 与 Content-Type 一起使用时出现 CORS 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆