AngularJS在使用method:POST时$resource调用错误的API URL

AngularJS $resource calls the wrong API URL when using method:POST

本文关键字:调用 resource 错误 URL API method POST AngularJS      更新时间:2023-09-26

不是最容易放入标题中的问题。

无论如何,我的应用程序是建立在nodejs/expressjs上,并为URL设置了一个API:

编辑:我正在使用的当前代码是:

$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而不是像我执行$scope.updateProduct.get()时那样/api/updateProduct/<product>/<param>/<value>

在我的控制台中,我看到(例如):

 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的方式肯定是错误的。

正如您在 ngResource 文档中看到的,$resource接收 3 个参数:

$resource(url[, paramDefaults][, actions]);

您将操作作为参数传递。

正确的版本是:

$scope.updateProduct = $resource('/api/updateProduct/:product/:param/:value',{}, {'save':{method:'POST'}});

请注意,这甚至不是必需的,因为当您使用 $resource 时,您已经创建了默认方法:

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

首先,您已经将save()定义为具有一个名为"brand"的参数,但是在您的 url 模板和对 save() 的调用中,您使用的是"product"。我想这是一个错字。

你说当你使用浏览器访问网址时,它工作得很好;但是当angular向同一个url发出PUT请求时,什么都没有发生。这表示您的后端配置为仅处理此特定 URL 模式的 GET 请求。因此,您需要确保您的后端接受 PUT 请求。

我一直在努力解决这个问题,并且能够通过执行下面的等效调用将参数传递给资源(请注意"保存"之前的"$")。

$scope.updateProduct.$save({
    product : $scope.post._id, 
    param: 'likes', 
    value: $scope.user._id
});  

我也没有在资源中定义"保存"方法。 根据Angular docs:

"调用这些方法(意味着非GET方法)使用给定的方法,参数和标头在url模板上调用$http。当从服务器返回数据时,该对象是资源类型的实例,并且所有非 GET 方法都带有 $ 前缀。这使您可以轻松支持对服务器端数据的 CRUD 操作(创建、读取、更新、删除)。