When working on a demo application recently I was trying to get an ajax call to hit one of my Web API routes and I was immediately hit with the following exception.
XMLHttpRequest cannot load http://localhost:33884/api/ToDo/. Origin http://localhost:3462 is not allowed by Access-Control-Allow-Orig
Of course this sucked because I KNEW what the issue was but not exactly how to solve it. Well solve it the way I wanted. Of course i could have just put both my sites (MVC project and WebAPI project) under the same web application in IIS to remove this but that was not an acceptable answer for my needs.
After a bit of searching online I thought I came across an solution that would work. I thought that I could just set the crossDomain switch in my ajax call as below to get it to work, but no dice.
$.ajax({
url: url,
type: 'Get',
crossDomain: true,
success: (data) = & gt; {
// do something here
},
error: (data) = & gt; { }
});
I found another suggestion telling me to change the dataType of request form json to jsonp as below, but as you may have guessed that did not work.
$.ajax({
url: url,
type: 'Get',
dataType: jsonp,
success: (data) = & gt; {
// do something here
},
error: (data) = & gt; { }
});
Finally at a bit more searching I found more information which suggested I needed to add a response header on the server side to allow ‘Access-Control-Allow-Origin’ and this Stack Overflow answer gave me all the details needed to make this happen in Web API. Once I implemented the solution inside my WebApi endpoints and REMOVED the 2 un-needed attributes in my .ajax call the world was a happy place and I was able to make cross domain calls to my other services.
Till next time,
Posted
02-10-2013 6:34 AM
by
Derik Whittaker