AngularJS With Asp.net Web API: $http post returning XMLHttpRequest cannot load: Response for preflight has invalid HTTP status code 405

前端 未结 2 415
抹茶落季
抹茶落季 2020-12-30 08:36

When trying to POST json to Asp.net web API server using $http it\'s returning the following error

XMLHttpRequest cannot load http://localhost:6         


        
相关标签:
2条回答
  • 2020-12-30 09:07

    @Rakeschand you were right and it was the issue of cors

    Cors

    I installed Cors in my project using nu-get command line

    Install-Package Microsoft.AspNet.WebApi.Cors
    

    and added the follwoing code in WebApiConfig.cs file from App_Start folder.

    var enableCorsAttribute = new EnableCorsAttribute("*",
                                                   "Origin, Content-Type, Accept",
                                                   "GET, PUT, POST, DELETE, OPTIONS");
    config.EnableCors(enableCorsAttribute);
    

    and removed the following from the web config

       <remove name="X-Powered-By" />
                        <add name="Access-Control-Allow-Origin" value="*" />
                        <add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" />
                        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
    

    $http started working just like the $.ajax was working

    but these things left me with some confusion. I would be great full if anyone can elaborate

    1. why the $.ajax was working and $http was not working
    2. I did the same thing by cors the I had done in web.config then why did cors worked but web.config didn't?
    0 讨论(0)
  • 2020-12-30 09:08

    I think you must set the content-type on your ajax call:

    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    

    or

    contentType: 'application/json; charset=utf-8',
    
    0 讨论(0)
提交回复
热议问题