将DELETE发送到服务器时出现错误405方法不允许错误

时间:2014-11-02 07:38:14

标签: java angularjs spring rest crud

我尝试删除时收到以下响应:405方法不允许。 在我的日志中写道允许GET,但DELETE不是。

爪哇:

   @ResponseBody
   @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
   public void delete(@PathVariable String id) {
     speakerService.delete(id);
   }

Angularjs

  app.factory('SpeakerResource', function ($resource) {
      return $resource('rest/speaker/:speakerId',
    {
        speakerId: '@speakerId'
    },
    {
        'update': { method: 'PUT' }
    },
     {
         'delete': { method: 'DELETE', params: { 'id': 'speakerId' }}

     }
    )
 });

SpeakerService

 this.delete = function (id, callback) {

    SpeakerResource.delete({ speakerId: id }, function () {
        callback();
    });

}

2 个答案:

答案 0 :(得分:4)

我不知道您的完整代码,我不是AngularJS的专家,但看起来您想要向网址<hopefullySomething>/{id}发送DELETE请求(路径变量) 。但看起来您发送了DELETE请求,因此某些URL的参数标识为<hopefullySomething>?id={id}请求参数)。

此问题和答案解释了路径变量和请求参数之间的差异@RequestParam vs @PathVariable

答案 1 :(得分:3)

使用$ http.delete(),并返回数据以获取示例状态,我刚刚使用spring测试了以下内容并正常工作

@RequestMapping(value = "delete/{id}", method = RequestMethod.DELETE)  
     public @ResponseBody  Status deletePerson(@PathVariable("id") int id) {      
          try { 
              personService.removePerson(id); 
           return new Status(1, "person deleted Successfully !");  
          } catch (Exception e) {  
           return new Status(0, e.toString());  
          }       
     }

有角度的

angular.module('personService', [])

.factory('Person', ['$http',function($http) {
    return {

        deletePerson: function(id) {
            return $http.delete('/restperson/delete/'+id);
        }
    }
}]);

控制器

angular.module('personController', [])

// inject the person service factory into our controller
.controller('mainController', ['$scope','$http','Person', function($scope, $http, Person) {     

    //delete
    $scope.deletePerson = function(id) {
        Person.deletePerson(id)
            .success(function(data) {
                $scope.message = data; 
            });
    };

}]);