启用CORS,但是POST POST时的响应具有无效的HTTP状态代码404 [英] CORS enabled but response for preflight has invalid HTTP status code 404 when POSTing JSON

查看:3239
本文介绍了启用CORS,但是POST POST时的响应具有无效的HTTP状态代码404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



使用Fiddler(POST)的跨网域服务调用正确执行,而且我们已经彻底搜索过,但在特定情况下找不到此问题的解决方案。数据。但是,通过浏览器(Chrome),我收到preflight有无效的HTTP状态代码404消息



我有一个Web API应用程序并安装了CORS,以下是存在于web.config文件中:

 < system.webServer> 
< handlers>
< remove name =ExtensionlessUrlHandler-Integrated-4.0/>
< remove name =OPTIONSVerbHandler/>
< remove name =TRACEVerbHandler/>
< add name =ExtensionlessUrlHandler-Integrated-4.0path =*。 verb =*type =System.Web.Handlers.TransferRequestHandlerpreCondition =integratedMode,runtimeVersionv4.0/>
< / handlers>
< httpProtocol>
< customHeaders>
< add name =Access-Control-Allow-Originvalue =*/>
< add name =Access-Control-Allow-Headersvalue =Content-Type/>
< add name =Access-Control-Allow-Methodsvalue =GET,POST,PUT,DELETE,OPTIONS/>
< / customHeaders>
< / httpProtocol>
< /system.webServer>

这是Ajax调用:

  VAR SecretKey的='difusod7899sdfiertwe08wepifdfsodifyosey',
URL ='http://api.intrinsic.co.uk/api/v1/PTS/ActiveDrivers?api_key=098werolllfWnCbPGAuIXVOJidDHRfYcgxImMlxTXopuekXrSOqOWzEAIdeNTWGPQPpyHxgVGsFysGFKPzq';

jQuery.ajax({
url:url,
type:POST,
data:JSON.stringify({secretKey:secretKey}),
dataType:json,
contentType:application / json; charset = utf-8,
success:function(data){
var content =& \container\>< THEAD>< TR><第i驱动器号< /第i个百分位>时间戳< /第i个百分位> VRN< /第i个百分位>纬度和LT ; /第i个百分位>经度< /第i个百分位>链轨< /第i< / TR>< / THEAD>< TBODY>中,
$。每次(data.ActiveDrivers .DriverLocationStatus,功能(索引,元素){
含量+ =< TR>< TD>中+ element.DriverNumber +< / TD>中,
含量+ =< td>+ dateFormat(element.Timestamp,d / m / yy)++ dateFormat(element.Timestamp,h:MM TT)+< / td>;
content + =< td>+ element.VRN +< / td>;
content + =< td>+ element.CurrentLatitude +< / td>
content + =< td> + element.CurrentLongitude +< / td>;
content + =< td>< a href = \https://www.google.co.uk/maps/place//@+ element.CurrentLatitude +,+元素。 CurrentLongitude +,15z / \target ='_ blank'> Track& raquo;< / a>< / td>< / tr>;
});
content + =< / tbody>< / table>;
$(#result).html(content);
}
});

显然,在同一域上工作是完全的,如前所述,它使用Fiddler工作。



我确定这是浏览器的预检OPTIONS检查是失败的内容类型的'application / json',但我不知道如何解决它。



在我要添加的web.config文件中缺少一些东西?



我已经尝试删除'content-type 没有影响。



我曾经希望这篇文章会解决这个问题(它似乎很有希望),但遇到相同的错误:

  XMLHttpRequest无法加载[URL]。回覆回应包含无效的HTTP状态码404 


解决方案


$ b

最后,在web api Global.asax文件中添加以下代码后,它会工作。

 保护无效的Application_BeginRequest(对象发件人,EventArgs五)
{
//HttpContext.Current.Response.AddHeader(\"Access-Control-Allow-Origin ,*);
如果(HttpContext.Current.Request.HttpMethod ==选项)
{
HttpContext.Current.Response.AddHeader(缓存控制,无缓存);
HttpContext.Current.Response.AddHeader(Access-Control-Allow-Methods,GET,POST);
HttpContext.Current.Response.AddHeader(Access-Control-Allow-Headers,Content-Type,Accept);
HttpContext.Current.Response.AddHeader(Access-Control-Max-Age,1728000);
HttpContext.Current.Response.End();
}
}


I've searched thoroughly but cannot find a solution to this issue in my particular circumstance.

Cross-domain service calls using Fiddler (POST) execute correctly and the data is received. However, through the browser (Chrome) I am getting the message 'preflight has invalid HTTP status code 404'

I have a Web API application and have installed CORS and ensured the following is present in the web.config file:

<system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Here is the Ajax call:

var secretKey = 'difusod7899sdfiertwe08wepifdfsodifyosey',
    url = 'http://api.intrinsic.co.uk/api/v1/PTS/ActiveDrivers?api_key=098werolllfWnCbPGAuIXVOJidDHRfYcgxImMlxTXopuekXrSOqOWzEAIdeNTWGPQPpyHxgVGsFysGFKPzq';

  jQuery.ajax ({
      url: url,
      type: "POST",
      data: JSON.stringify({ secretKey: secretKey}),
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      success: function(data){
          var content = "<table class=\"container\"><thead><tr><th>Driver Number</th><th>Timestamp</th><th>VRN</th><th>Latitude</th><th>Longitude</th><th>Track Link</th></tr></thead><tbody>";
          $.each(data.ActiveDrivers.DriverLocationStatus, function (index, element) {
              content += "<tr><td>" + element.DriverNumber + "</td>";
              content += "<td>" + dateFormat(element.Timestamp, "d/m/yy") + " " + dateFormat(element.Timestamp, "h:MM TT") + "</td>";
              content += "<td>" + element.VRN + "</td>";
              content += "<td>" + element.CurrentLatitude + "</td>";
              content += "<td>" + element.CurrentLongitude + "</td>";
              content += "<td><a href=\"https://www.google.co.uk/maps/place//@" + element.CurrentLatitude + "," + element.CurrentLongitude + ",15z/\" target='_blank'>Track &raquo;</a></td></tr>";
          });
          content += "</tbody></table>";
          $( "#result" ).html( content );
      }
  });

Obviously, works on the same domain perfectly and, as mentioned, it works using Fiddler.

I'm certain it is the brower's preflight OPTIONS check that is failing for content-type of 'application/json' but I'm not sure how to fix it.

Is there something missing in the web.config file that I should add?

I have tried removing 'content-type' with no affect.

I had hoped this article would solve the issue (it seemed promising) but the same error is encountered:

XMLHttpRequest cannot load [URL]. Response for preflight has invalid HTTP status code 404

解决方案

Thanks but getting 405 error,after the above config changes.

Finally it works after adding below code in web api Global.asax file

protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        //HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

这篇关于启用CORS,但是POST POST时的响应具有无效的HTTP状态代码404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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