0

我有以下代码,一个消耗 API 休息的工厂:

angular.module('teachers')
.factory("TeachersService",
    function($resource) {

     var restPath = 'http://localhost:8001/entities/teacher/';

     return $resource(restPath + ':id', { id: "@teacherId" }, {

         'getSubjects': {
             method: 'GET',
             url: restPath + ':id' + '/subject',
             isArray: true
         },

         'update': { method: 'PUT'},

         'getClasses': {
             method: 'GET',
             url: restPath + ':id' + '/class',
             isArray: true
         }

     });


    });

在控制器中,我使用工厂:

        vm.teacher = TeachersService.get({id: vm.teacherId}, function() {
            console.log(vm.teacher)
        }, function() {
            console.log('Teacher not found')
            vm.teacher = null;
        })

数据检索得很好,但现在我需要更新这个实体的数据,我想使用工厂有的更新方法:

            vm.teacher.$update(function() {
                console.log('success')
            }, function(error){
                console.log('error')
                console.log(error)
            });

但我不知道为什么它总是让我失败(这些方法适用于 curl 和其他程序,如邮递员)。

这是失败标头的示例:

对象{数据:空,状态:-1,标题:fd/<(),配置:对象,状态文本:“”}

我不明白发生了什么,我认为问题出在我传递 id 的方式上。我确定实体vm.teacherteacherId一个整数值,但我不知道为什么没有通过。另外,我看到了 Firefox 的网络控制台(在我的情况下),我看到对服务器的调用不存在,但是当我将定义更改为 id 时,例如:

{ id: "@_teacherId" }

调用完成但出现错误,因为 url 最后没有实体标识符,而 PUT 方法中的服务器需要它。

假用户的一个例子是(在得到它之后):

Object { createdBy: 1, phone: "+34740 51 73 72", createdAt: "Tue Oct 25 12:58:30 2016", name: "Alvaro", address: "Callejón Lourdes Pozuelo 11 Apt. 54…", teacherId: 4, $promise: Object, $resolved: true }

任何想法?我被屏蔽太多次了。

谢谢!

编辑

如果我更改代码并设置 GET 方法调用它:

         'update': {
             method: 'GET',
             url: restPath + ':id'
         }

但不是当方法是 PUT 时:

         'update': {
             method: 'PUT',
             url: restPath + ':id'
         }
4

1 回答 1

1

最后,问题出在 Flask API 中,我需要启用跨域资源共享 ( CORS ) 机制。正因为如此,我一次又一次地尝试了这些示例,但没有成功,问题不在于最后的 $resource 代码。

状态 -1 表示 AngularJS 内部错误,例如超时或同源策略/CORS 问题。感谢@georgeawg。

在服务中,代码很好:

'update': {method: 'PUT'},

在控制器中也很好:

 vm.teacher.$update()

在我的烧瓶 api 中,我需要添加以下内容:

from flask.ext.cors import CORS, cross_origin
...
app = Flask(__name__)
CORS(app)

文档中有关 flask-core 的更多信息:flask-cors

于 2016-11-03T17:23:06.810 回答