0

I have a node.js application with Express for routing and Mongoose for the database access.

I have this HTTP DELETE request that is deleting an entry in the database if certain requirements are met.

    .delete(function (req, res) {

    Movie.findOne({_id: req.params.id

    }, function (err, movie) {
        if (err)
            res.send(err);

        for (var i = 0, len = movie.actors.length; i < len; i++) {
            if (movie.actors[i].actor == "Chuck Norris"){
                res.status(403).send({ message: 'Cannot delete Chuck Norris' });
              }
            else {
                Movie.remove({_id: req.params.id
                }, function (err, movie) {
                    if (err)
                        res.send(err);

                    res.json({message: 'Movie deleted'});
                });


    }
        }

    });

});

If I send a HTTP DELETE with the ID of a film, it will check in the actors list if Chuck Norris is in the movie and I will prevent the deletion if he is there.

The problem is that my console is returning me this error :

Error: Can't set headers after they are sent.

So I presume that this an issue with my callbacks. Due to the asynchronus nature of node.js the "slow" database call made that my .delete sent the headers before the findOne finished ?

How can I manage to validate before deletion and send a proper http error code if the deletion is not possible ?

1 Answer 1

1

Be careful when you respond to a request multiple times in the same scope like that. On error you should prepend return to res.send(err) so that execution will not continue further. The same goes for your res.status() in the for-loop.

Sign up to request clarification or add additional context in comments.

1 Comment

I changed it to a return and tweaked the rest a little bit and it works now. Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.