AngularJS $resource 在使用 method:POST 时调用了错误的 API URL [英] AngularJS $resource calls the wrong API URL when using method:POST
问题描述
不是最容易放入标题的问题.
Not the easiest issue to put into a title.
无论如何,我的应用程序是基于 nodejs
/expressjs
构建的,并且为 url 设置了一个 API:
Anyhow, my app is built on nodejs
/expressjs
and has an API set up for the url:
我当前使用的代码是:
$scope.updateProduct = $resource('/api/updateProduct/:product/:param/:value',{},{
query: {method:'GET'},
post: {method:'POST'},
save: {method:'PUT', params: {brand: '@brand', param:'@param', value:'@value'}},
remove: {method:'DELETE'}
});
$scope.updateProduct.save({
product : $scope.post._id,
param: 'likes',
value: $scope.user._id
});
目前它调用 /api/updateProduct
而不是 /api/updateProduct/
就像它应该的那样/就像我执行 $scope.updateProduct.get()
时那样.
At present it calls /api/updateProduct
instead of /api/updateProduct/<product>/<param>/<value>
like it's supposed to / like it does when I perform $scope.updateProduct.get()
.
在我的控制台中,我看到(例如):
In my console I see (as an example):
PUT /api/updateBrand/Quay%20Eyewear%20Australia/userTags/sunglasses,%20classic 200 30ms - 2.31kb
但是,实际上并未访问 API/没有任何反应.有趣的是,如果我在浏览器中访问 localhost:5000/api/updateBrand/Quay%20Eyewear%20Australia/userTags/sunglasses,%20classic
,它会发布正确的数据并更新我数据库中的产品,所以这肯定是 $resource
被调用的方式错误.
However, the API isn't actually accessed/nothing happens. Interestingly, if I go to localhost:5000/api/updateBrand/Quay%20Eyewear%20Australia/userTags/sunglasses,%20classic
in my browser, it posts the correct data and updates the product in my database, so it's definitely an error with the way the $resource
is being called.
推荐答案
正如您在 中所见ngResource docs, $resource
接收3个参数:
As you can see in ngResource docs, $resource
receive 3 parameters:
$resource(url[, paramDefaults][, actions]);
您将操作作为参数传递.
You are passing your action as a parameter.
正确的版本是:
$scope.updateProduct = $resource('/api/updateProduct/:product/:param/:value',{}, {'save':{method:'POST'}});
请注意,它甚至不是必需的,因为当您使用 $resource
时,您已经创建了默认方法:
Note that it isn't even necessary, because when you use $resource
you already create the default methods:
{
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
这篇关于AngularJS $resource 在使用 method:POST 时调用了错误的 API URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!