gpt4 book ai didi

javascript - Angular 资源 : Error: $resource:badcfg

转载 作者:可可西里 更新时间:2023-11-01 13:46:14 24 4
gpt4 key购买 nike

我已查看此处的其他帖子,但仍无法解决我的问题。

我得到一个错误:

$resource:badcfg Response does not match configured parameter

我相信这个错误是由于它返回一个数组而不是一个对象引起的,反之亦然。

这是我的代码:

在我的工厂里(我添加了 isArray: false 但还是不走运)

var task = $resource('http://localhost:5000/task/:id', {id:'@id'}, {
'get': {method:'GET', isArray: false},
});

然后在我工厂的返回区

    find: function(id){
return task.get({ id: id });
}

在我的 Flask 服务器中,当我加载页面时它会做出正确的响应:

127.0.0.1 - - [28/Feb/2017 14:35:13] "GET /task/1 HTTP/1.1" 200 -

但是还是报错?

这也是我的服务器提供的,如果我把它放在浏览器中 http://localhost:5000/task/1

[{"completed": true, "id": 1, "ownerName": "Ryan", "task": "Test Activity", "title": "A test task"}]

我也试过这个并得到同样的错误:

console.log(task.get({ id: 1 }));

最佳答案

This error occurs when the $resource service expects a response that can be deserialized as an array but receives an object, or vice versa. By default, all resource actions expect objects, except query which expects arrays.

To resolve this error, make sure your $resource configuration matches the actual format of the data returned from the server.

--AngularJS Error Reference - $resource:badcfg

$resource 的默认操作是:

{ 'get':    {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };

避免更改默认方法:

var task = $resource('http://localhost:5000/task/:id', {id:'@id'}, {
//AVOID changing default
//'get': {method:'GET', isArray: true},
});

改为使用query 操作方法:

find: function(id){
//return task.get({ id: id });
//INSTEAD use query action method
return task.query({ id: id });
}

这将避免混淆熟悉 $resource 服务约定的程序员。

有关详细信息,请参阅 AngularJS $resource API Reference .


使用transformResponse从数组中提取对象

如果服务器错误地返回包含在数组中的资源对象,可以使用响应转换函数将其提取出来:

var task = $resource('http://localhost:5000/task/:id', {id:'@id'}, {
'get': {method:'GET',
transformResponse: function(json) {
var data = angular.fromJson(json);
if ((typeof data == 'array' && (data.length == 1)) {
return data[0];
} else {
return data;
};
}
}
});

关于javascript - Angular 资源 : Error: $resource:badcfg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42511984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com