Connect to API endpoint with Angular factory

2019-06-07 02:02发布

问题:

I am trying to connect with API endpoint via the simplest AngularJS snippet but have some problems which are stopping me.

Here is my controller:

app.controller('appController', ['$scope', 'skills',
 function($scope, skills) {
 skills.success(function(data) {
  $scope.skillsList = data;
});
  }
]);

And my factory:

app.factory('skills', ['$http', function($http) { 
  return $http.get('https://www.persevy.com/skills') 
        .success(function(data) { 
          return data; 
        }) 
        .error(function(err) { 
          return err; 
        }); 
}]);

I have even prepared a Plunkr for this but also without success, please tell me where is the problem in the above code.

回答1:

In your RoR API in app/controllers/application_controller.rb:

before_filter :add_allow_origin_headers

def add_allow_origin_headers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
  response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*'                                                                                                                                                                                                                         
end 

Or you can use a gem called rack-cors

#Gemfile
gem 'rack-cors'

#config/application.rb
config.middleware.use Rack::Cors do
   allow do
     origins '*'
     resource '*', :headers => :any, :methods => [:get, :post, :options]
   end
end

This will allow the requests from different applications, fixing the issue for you.
More information on the rack-cors gem here



回答2:

Your issue seems related to CORS : basically, you cannot access a domain via Ajax if it's not allowed on the server side. This is a "security" feature on most modern browser. You won't encounter this problem using command line such as curl or Postman chrome's extention.

If you own the domain https://www.persevy.com/, make sure the domain requesting the data is allowed in the Access-Control-Allow-Origin header, as well as the http verb (GET, POST, PUT... or * for every http methods).

If you are using an API, you should find something in the documentation regarding that matters.

Edit

I'm a bit rusty in RoR, but from my googling, looks like you can use the rails-cors gem, or try this gist.

Basically, it comes down to add the two following headers to the server's response :

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *