将Content-Type与访存一起使用时发生CORS错误 [英] CORS error when using fetch with Content-Type

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

问题描述

我正在尝试从FireFox中的其他域向REST Web服务发送POST请求.我正在使用JavaScript抓取"功能.我在IIS中托管REST Web服务.在我添加"Content-Type"之前,它工作正常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.

CORS错误

请注意,如果我在控制台中启用了XHR,则可以看到使用带有"Content-Type"的抓取功能.导致一个OPTIONS请求.但不使用"Content-Type"导致POST请求.因此,抓取操作会触发预检请求,如文档所述.这些是错误:

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.

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));

我使用的是凭据:" include"因为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服务将无法工作.标头"application/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错误都与Daniel指出的一样

这是我修改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服务.但是我没有在其中写任何添加heaaders,因为它似乎推翻了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" )

<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>

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

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