Angularjs- $ ngResource:当我按id删除某些内容时,它显示403错误

时间:2016-04-23 05:21:38

标签: angularjs spring-mvc

这是删除按钮:

<td><input type="button" value="delete" ng-click="deleteUser(u.id)"></td>

这是JS文件:

var app = angular.module('MyApp', ['ngResource']);


app.factory('baseRequest', ["$resource", function ($resource) {

    return $resource("/apis/:method/:id", {method:'@method',id: '@id'}, {

        query: {method: 'get', isArray: false}

    });

}]);


app.controller("MyCtrl", ["$scope", "baseRequest", function ($scope, baseRequest) {

    $scope.users = [];


    $scope.fetchAllUsers = function () {

        $scope.users = baseRequest.query({method: "getPageData.req"});

        console.log($scope.users);
    };

    $scope.fetchAllUsers();


    /**
     *   here is the delete method
     * 
     **/

    $scope.deleteUser = function (id) {

        baseRequest.delete({method: "deleteUser.req", id: id}, function (response) {

            console.log(response);

        }, function (error) {

            console.log(error);

        });
    };

}]);

现在当我点击删除按钮时,它显示如下错误:403,禁止访问指定资源。

请求信息:

请求网址:http://localhost:8080/apis/deleteUser.req/2 请求方法:DELETE 状态代码:403 远程地址:[[:: 1]]:8080

这是SpringMVC控制器:

@RequestMapping("/apis")
@Controller
public class UserController {

    @Autowired
    private UserDao userDao;


    @ResponseBody
    @RequestMapping(value = "/getPageData", method = RequestMethod.GET)
    public Page<User> getDatas(@RequestParam(value = "pageNo", required = false, defaultValue = "1") String No) {

        int pageNo = Integer.parseInt(No);

        if (pageNo < 0) {

            pageNo = 1;
        }

        return userDao.getPageData(pageNo);
    }

    @ResponseBody
    @RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable("id") Integer id) {

        System.out.println(id);

        if (userDao.deleteUser(id)) {

            return "1";

        } else {

            return "0";
        }

    }
}

2 个答案:

答案 0 :(得分:0)

看起来它是服务器端映射问题,但您可以尝试将不同的参数传递给delete的{​​{1}}操作。尝试更改它:

$resource

baseRequest.delete({method: "deleteUser.req", id: id}, function (response) {})

答案 1 :(得分:0)

我想我找到了解决这个问题的答案。关键是当您使用后缀URL(如/XX.req)传输参数时,会发生此错误:服务器端无法识别此请求。

例如:

错误:localhost:8080 / apis / deleteUser.req / 2

右:localhost:8080 / apis / deleteUser / 2

也许我应该尝试一下:(我还没有测试过) http://localhost:8080/apis/2/deleteUser.req

=============================================== ======

在我测试了上述想法后,两者都运作良好。当然,我们应该使用最后一个。

本地主机:8080 / API的/ 2 / deleteUser.req

所以,我只是交换URL参数的位置,如下所示:

$ resource(“/ apis /:id /:method /”,{method:'@ method',id:'@ id'}