【问题标题】:ngResource ($resource) is returning 404 for PUTngResource ($resource) 为 PUT 返回 404
【发布时间】:2016-12-10 04:45:30
【问题描述】:

我已经有一段时间没有使用 $resource 来管理我的服务调用了。

出于某种原因,我的所有调用都正常运行并到达了我的 REST 端点,基本上是 /api/profile 和 /api/profile/:id。

但由于某种原因,我的 put 返回为 404。

任何人都知道可能发生的事情。

感谢和干杯!

'use strict';

angular.module('chainLinkApp')

.config(['$stateProvider', function($stateProvider){
  $stateProvider
  .state('profile', {
    url:'/profile/:id',
    templateUrl:'views/profile.html',
    controller:'ProfileController',
    controllerAs:'profile'
  });
}])

.controller('ProfileController',['$scope', '$http', 'profileFactory', function($scope, $http, profileFactory){


  $scope.updateMode = false;


  $scope.comments = profileFactory.getProfiles.go().$promise.then(function(response){
    $scope.comments = response;
  });


  $scope.getProfile = function(commentId){
    $scope.comment = profileFactory.getProfile.go({id:commentId}).$promise.then(function(response){
      $scope.comment = response;
      $scope.updateMode = true;
    }, function(error){
      return console.log('An error has occured', error);
    });
  };


  $scope.addProfile = function(comment){
    profileFactory.postProfile.go(comment).$promise.then(function(){
      console.log('Your post was a success');
      $scope.comment = {};
    }, function(error){
      console.log('There was an error: ', error);
    });
  };


  $scope.updateProfile = function(comment){
    profileFactory.updateProfile.go(comment._id, comment).$promise.then(function(response){
      console.log('Your profile has been updated');
      $scope.updateMode = false;
      $scope.comment = {};
    }, function(error){
      console.log('There is an error: ', error);
    });
  };
}])


.factory('profileFactory', ['$resource', function($resource){

  return{
    getProfiles:    $resource('/api/profile', {}, { go: { method:'GET', isArray: true }}),
    getProfile:     $resource('/api/profile/:id',{},{ go: { method: 'GET', params: { id: '@id' }}}),
    postProfile:    $resource('/api/profile', {}, { go: { method: 'POST' }}),
    updateProfile:  $resource('/api/profile/:id', {}, { go: { method: 'PUT', params: { id:'@id' }}})
  };

}]);

【问题讨论】:

  • 问题可能出在你的服务器端,检查你那里的映射。
  • 尝试将 {_method: 'PUT'} 添加到您的请求中,某些服务器无法使用真正的 PUT。

标签: angularjs ngresource angularjs-ng-resource


【解决方案1】:

你使用$resource的方式很奇怪,应该是这样的:

.factory('UserService', function($resource) {
    return $resource('/api/users/:id', {}, {
        'create': { method: 'POST' },
        'update': { method: 'PUT', params: { id: '@id'} }

    });
})

然后你像这样调用服务:UserService.create(theUserobj, function(result) { ... })

【讨论】:

  • 谢谢马夫兰。你说的对。自从我使用它以来已经有一段时间了,我试图链接各种调用,包括一些自定义调用。
  • OK,反正你的代码好像没有问题。您是否检查了更新请求中的网址?哪个应该与服务器端的代码匹配。请检查您网址中的“id”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 2020-02-05
  • 2017-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多