Javascript 使用expressrestapi编辑文章

Javascript 使用expressrestapi编辑文章,javascript,node.js,mongodb,angularjs,express,Javascript,Node.js,Mongodb,Angularjs,Express,我有一个有mongoose和mongoDB的angular express应用程序 对于角度部分,我有: .controller('EditPostCtrl', ['$scope', '$http', '$location', '$routeParams', function($scope, $http, $location, $routeParams){ // populate the form $scope.form = {}; $http.get('/api/pos

我有一个有mongoose和mongoDB的angular express应用程序

对于角度部分,我有:

.controller('EditPostCtrl', ['$scope', '$http', '$location', '$routeParams', function($scope, $http, $location, $routeParams){
    // populate the form
    $scope.form = {};
    $http.get('/api/post/' + $routeParams.post_id)
        .success(function(data){
            $scope.form = data;
        });

    // save changes and redirect
    $scope.editPost = function(){
        $http.put('/api/post/' + $routeParams.post_id, $scope.form)
            .success(function(data){
                $location.url('/post/' + $routeParams.post_id);
            });
    };
}])
那么对于快速部分,我有一条路线:

app.put('/api/post/:post_id', posts.editPost);


exports.editPost = function(req, res){
    var updatedPost = {
        title: req.body.title,
        text: req.body.text,
        created: req.body.created
    };

    Post.update({ _id: req.body._id }, updatedPost, function(err, affected){
        console.log('affected %d', affected);
    });
};

启动服务器后,我可以更新帖子,但在编辑后,我不会像我在angular中声明的那样重定向到
'/post/'+$routeParams.post_id
。editPost函数中需要什么?

您需要向客户端发送并应答,例如,所有内容都已更新,但没有返回任何内容(204):


另请参见。

好的,这是可行的,但我从未见过204在其他人的代码中使用过,有没有更好的方法可以根据我的角度编辑记录?有人可能会说,在更新后,服务器应该将更新的实体返回为带有200的主体。我在代码中添加了一个示例-我希望我正确理解mongoose:)您也可以尝试相应地使用和创建Express服务
exports.editPost = function(req, res){
    var updatedPost = {
        title: req.body.title,
        text: req.body.text,
        created: req.body.created
    };

    Post.update({ _id: req.body._id }, updatedPost, function(err, affected){
        console.log('affected %d', affected);

        //returns with no body, but OK:
        //res.send(204);
        //returns with update entity as body:
        res.send(200, updatedPost);
    });
};