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
@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
$.ajax
was working and $http
was not workingcors
the I had done in web.config
then why did cors
worked but web.config
didn't?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',