Arvind Agrahari Arvind Agrahari - 3 months ago 31
jQuery Question

XMLHttpRequest can not load. Response for preflight has invalid HTTP status code 405

I have read many similar problems in StackOverflow, but the solutions don't work for me.
I can use it using Postman (Chrome extension). I am passing data as 'Header'. And I get 200 return code.

enter image description here

I need to call this method using ajax Jquery :

$.ajax(apiUri, {
beforeSend: function (xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + $('#AccessToken').val());
},
dataType: 'text',
cache: false,
success: function (data) {
console.log(data);
$('#output').text(data);
}
});


But in this case, I got an error.

Like console error using jquery/Ajax

At Resource server side I have set in web.config.

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

Answer

I just put in global setting

    protected void Application_BeginRequest()
    {
        if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
        {
            Response.Flush();
        }
    }

and did some changes in web.config(system.webserver) settings

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

then working fine :)

Thanks