CORS–AngularJS : No ‘Access-Control-Allow-Origin’ header is present on the requested resource. web api angularjs


So recently , I am working on angularjs project with backend in asp.net web api. In my case, both projects are separate so one is running on localhost:9333  & other one on localhost:8333. Now I publish web api on our server and url will be like  https://xyz.com/api/reference/1001

Now I want to access that web api in my angularjs project directly in angularjs controllers so that I don’t have to involve any mvc controller in between. I tried and I got this error :

“No ‘Access-Control-Allow-Origin’ header is present on the requested resource. web api angularjs”

no ‘access-control-allow-origin’ header is present on the requested resource. origin localhost ….

So , I spend few hours to search on it , everyone said that I have to set CORS configuration on my web api level to allow origins, which I didn’t wanted to do.

Finally I found the solution at https://github.com/jpillora/xdomain

It’s kind of offline proxy providers for your localhost site.

How to install & Config : Very simple

1) Create one proxy.html on your server where you have api  (or any web site) with content as below –

<!DOCTYPE HTML>
<script src=”//rawgit.com/jpillora/xdomain/gh-pages/dist/0.6/xdomain.js” master=”*”></script>
2) in your localhost / slave site –

<script src=”https://rawgit.com/jpillora/xdomain/gh-pages/dist/0.6/xdomain.js” slave=”http://xyz.com/proxy.html”></script>
3) That’s it. Now you can access the api in angularjs like –

var states = $http.get(‘http://xyz.com/api/reference/1004′) // This will be your published api url
.success(function(data){
       console.log(data);
   });

 

My plnkr demo : http://plnkr.co/edit/ZRjs1x

Happy Coding… Smile

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s