Connor Leech
Connor Leech

Reputation: 18834

edit posts using express REST API

I've got an angular-express app with mongoose and mongoDB

for the angular portion I have:

.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);
            });
    };
}])

Then for the express portion I have a route:

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);
    });
};

After I start the server I can update posts but after the edit I don't get redirected to '/post/' + $routeParams.post_id like I declare in angular. What do I need in the editPost function?

Upvotes: 1

Views: 1652

Answers (1)

Sonata
Sonata

Reputation: 2217

You need to send and answer to the client, for instance that everything was updated, but no content is returned (204):

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);
    });
};

See also Express API.

Upvotes: 3

Related Questions