Angularjs剥离尾随斜杠

时间:2015-07-21 09:56:51

标签: angularjs

我在控制器中有一个功能:

  $scope.deleteTodo = function(id) {
        $http.delete('/musicians/' + id)
            .success(function(data) {
                $scope.todos = data;
                console.log(data);
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

我称之为:

 <button class="btn btn-default" type="button" ng-click="deleteTodo(todo._id)" >

它给网址带来404错误:

http://localhost:3000/musicians55accbce27e2cd2802de4894 Failed to load resource: the server responded with a status of 404 (Not Found)

但是,应该是:

http://localhost:3000/musicians/55accbce27e2cd2802de4894

我也尝试添加:

.config(['$resourceProvider', function($resourceProvider) {
  // Don't strip trailing slashes from calculated URLs
  $resourceProvider.defaults.stripTrailingSlashes = false;
}]); 

但它也没有解决问题,我仍然遇到同样的问题。

以下是调用它的流程:

 app.delete('/musicians/:id', musicians.delete);

exports.delete = function(req, res){
  var id = req.params.id;
  Musician.remove({'_id':id},function(result) {
    return res.send(result);
  });
};

3 个答案:

答案 0 :(得分:0)

不确定问题是什么,但您是否尝试在调用$http之前编译url字符串,看看是否修复了它?例如:

$scope.deleteTodo = function(id) {
        var url = '/musicians/' + id;
        $http.delete(url)
            .success(function(data) {
                $scope.todos = data;
                console.log(data);
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

答案 1 :(得分:0)

只是在黑暗中刺,但你尝试过使用原始的$http方法吗?

$scope.deleteTodo = function(todoId) {
    return $http({ 
        url: '/musicians', 
        method: 'DELETE', 
        data: { id: todoId }
    });
}

答案 2 :(得分:0)

您可以尝试转义片段:

$scope.deleteTodo = function(id) {
    $http.delete('/musicians\\/' + id)
        .success(function(data) {
            $scope.todos = data;
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
};

但是,我建议重新评估你如何调用你的删除方法。您希望调用资源项本身的删除,并且不将资源的id传递给catch all delete方法。请参阅http://docs.angularjs.org/api/ngResource/service/ $ resource