使用 Angular 工厂连接到 API 端点 [英] Connect to API endpoint with Angular factory

查看:20
本文介绍了使用 Angular 工厂连接到 API 端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过最简单的 AngularJS 代码段与 API 端点连接,但有一些问题阻止了我.

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

这是我的控制器:

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

还有我的工厂:

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

我什至为此准备了一个 Plunkr 但也没有成功,请告诉我上面代码的问题在哪里.

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

推荐答案

您的问题似乎与 CORS 有关 :基本上,如果服务器端不允许,则无法通过 Ajax 访问域.这是大多数现代浏览器的安全"功能.使用 curlPostman chrome 扩展等命令行不会遇到这个问题.

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.

如果您拥有域 https://www.persevy.com/,请确保请求的域Access-Control-Allow-Origin 标头中允许数据,以及 http 动词(GETPOSTPUT... 或 * 用于每个 http 方法).

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).

如果您正在使用 API,您应该在文档中找到与此相关的内容.

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

编辑

我对 RoR 有点生疏,但从我的谷歌搜索来看,您似乎可以使用 rails-cors gem,或者试试这个要点.

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: *

这篇关于使用 Angular 工厂连接到 API 端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆