简体   繁体   中英

XMLHttpRequest cannot load URL. Response for preflight has invalid HTTP status code 405

Doing a simple POST with jquery ajax to an IIS vb.net webservice

<html>
    <head>
        <script type="text/javascript" src="./js/jquery-3.1.1.min.js"></script>
        <script type="text/javascript" src="./js/json-2.4.min.js"></script>
        <script type="text/javascript" src="./js/util.js"></script>
    </head>
    <body>
    <script type='text/javascript'>
        var myKeyVals = { userid : "USERID", password : "password", gkey : "key"}
        $.ajax({
            url: "myurl",
            type: "POST",
            data: JSON.stringify(myKeyVals),
            contentType: "application/json",
            cache: false,

            success: function( data, textStatus, jQxhr ){
                alert(JSON.stringify(data))
            },
            error: function( jqXhr, textStatus, errorThrown ){
                alert("error")
            }
        });
    </script>

    </body>
</html> 

It seems to be working with IE but Chrome and Firefox throw the

"XMLHttpRequest cannot load url. Response for preflight has invalid HTTP status code 405" error

My web.config has

  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>

and also

<handlers>
     <remove name="OPTIONSVerbHandler" />
     <add name="OPTIONSVerbHandler" path="*" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" preCondition="bitness32" />
</handlers>

as per numerous other posts.

So In my case I didn't have a global.asax so I needed to create one by right clicking on my project and adding a new item. From there you can add a Global.asax. Within the Global.asax I had to do the following in the BeginRequest sub

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        'HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        If HttpContext.Current.Request.HttpMethod = "OPTIONS" Then
            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()
        End If
    End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM