[ Update : the site upon the article is based on , corsproxy.com is down, so the codes shown here will not work. We’ll replace it with another source soon. ]
Many a times we have this Ajax request or API call to a remote server using POST (I know you were just thinking about JSONP but that’s a GET) and they have not white listed our domain, I mean we can’t simply send Cross Domain Ajax Request. It’s part of the browser standard spec that they won’t, not that they can’t. For example the PostMan application in Google Chrome will let you do cross domain calls BUT that’s a packaged compiled app – like a standalone application you can say, and certainly not quite a browser. In packaged app they can modify the header to behave like that the request is coming from the same origin. We call it Cross Origin Resource Sharing or CORS in short.
Anyways, without further talks let’s look at the problem first – what happens when we send cross domain ajax request. We’ll be showing the exmaple with AngularJS (Muhaha).
Fixing Cross Domain Ajax Request
Now, in the console (when you run this JSBIN in separate window) you see that the error says:
XMLHttpRequest cannot load http://muslimsalat.com/daily.json. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://run.jsbin.io‘ is therefore not allowed access.
That means you can’t possibly send cross domain Ajax request. Now what to do ? We can ask the host to whitelist our domain but that’s not possible most of the cases when we are using APIs at times. Next option is to use a local proxy to modify the request header. There’s a nodejs project called CORS-Proxy here https://github.com/gr2m/CORS-Proxy – which will let you route all your request to the remote server. You will essentially make request to the nodeproxy and it will send it to remote server. It’s pretty easy to use. All you need to do is spawn the program and use a modified url like
http://localhost:9292/my.domain.com/path/to/resource
But this has its downside. I have personally used it and sometimes it breaks with an error and the program has to be spawned again. Now, people are very smart these days and lot of tools are available. There were hardly any tools back in our days when we used to write document.all && document.layers.
Okay, the online proxy available is http://www.corsproxy.com/ which works quite the same as the nodejs but it’s an online proxy which you can use and it will not possibly break.
So let’s get to the modified JSBIN and see if our request is working or not.
Fixing Cross Domain Ajax Request
So, you’re good to go for making Cross Domain Ajax POST requests.