im getting CORS header ‘Access-Control-Allow-Origin’ missing in angularjs

14,332

As mentioned in the comments, you will have to use a proxy, or some sort of proxy. There is no way around this.

However, it is fairly straightforward: make the server that serves the angularjs application do the api call.

First, you have to understand what server and client is. Afterwards, you need to understand that your angularjs application is served from a server. Your angularjs application can make http requests to that server, which will in turn make the call to the api, and return the result to the client:

crudely drawn diagram

I am somewhat assuming a Node server is serving your angularjs application, but any server can do the same, it will be able to make the http request without being a cross origin request.


In your case, when you do the url call, instead, call the server that serves your application, and then, from that server, create a service that will call the external api.

Share:
14,332
Swapna
Author by

Swapna

Updated on June 05, 2022

Comments

  • Swapna
    Swapna almost 2 years

    I'm getting a CORS header missing error. I can't modify the code of the back end web service, I can only change the client side application.

    I can add the "Allow control allow origin" addon on google chrome but I don't want to install the add on all the clients to access the api. How can i change my AngularJS code so that I will not get this issue?

    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope, $http) {
        $http.get('url', {
            headers: { 'Authorization': 'Basic a2VybmVsc3B==' }
        })
            .then(function (response) {
                $scope.names = response.data;
            });
    });
    </script>
    
  • charlietfl
    charlietfl over 7 years
    OP clearly stated they don't have back end access. How is this going to help?
  • charlietfl
    charlietfl over 7 years
    finally a sane answer!
  • charlietfl
    charlietfl over 7 years
    worth mentioning that there are third party proxy services also. Personally I don't like using no-name ones but that option does exist
  • Félix Adriyel Gagnon-Grenier
    Félix Adriyel Gagnon-Grenier over 7 years
    good point. However I rarely (never) use those, hence I am a bit hesitant to explain about that. will update if I feel I can add something worthwhile
  • charlietfl
    charlietfl over 7 years
    I have used several different ones that Yahoo supported. One is dead , was called pipes and was pretty cool. The other YQL is still alive and can do a lot of different things....xml to json, html scraper , straight json retrieval among a few