简体   繁体   中英

Can't set headers after they are sent error on PUT request

I get the Can't set headers after they are sent error everytime I try a PUT request on the specified route. And I couldn't figure out whats the problem here. I am also getting a 200 response, but the data is not updated in the database.

Here is my code:

episodeRouter.route('/:episodeId/comments/:commentId')
.get(Verify.verifyOrdinaryUser, function (req, res, next) {
    Episode.findById(req.params.episodeId)
        .populate('comments.postedBy')
        .exec(function (err, episode) {
            if (err) next(err);
            res.json(episode.comments.id(req.params.commentId));
        });
})

.put(Verify.verifyOrdinaryUser, function (req, res, next) {
    // We delete the existing commment and insert the updated
    // comment as a new comment
    Episode.findById(req.params.episodeId, function (err, episode) {
        if (err) next(err);
        episode.comments.id(req.params.commentId).remove();

        req.body.postedBy = req.decoded._id;

        episode.comments.push(req.body);
        episode.save(function (err, episode) {
            if (err) next(err);
            res.json(episode);
        });
    });
})

.delete(Verify.verifyOrdinaryUser, function(req, res, next){
    Episode.findById(req.params.episodeId, function (err, episode) {
        if (err) next(err);
        episode.comments.id(req.params.commentId).remove();
        episode.save(function(err, resp) {
            if (err) next(err);
            res.json(resp);
        });
    });
});

This is the error I get:

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
at ServerResponse.header (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\response.js:719:10)
at ServerResponse.send (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\response.js:164:12)
at done (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\response.js:956:10)
at Object.exports.renderFile (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\jade\lib\index.js:374:12)
at View.exports.__express [as engine] (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\jade\lib\index.js:417:11)
at View.render (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\view.js:126:8)
at tryRender (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\application.js:639:10)
at EventEmitter.render (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\application.js:591:3)
at ServerResponse.render (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\response.js:960:7)
at H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\app.js:91:7
at Layer.handle_error (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\router\index.js:310:13)
at H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\router\index.js:280:7
at Function.process_params (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\router\index.js:330:12)
at next (H:\COURSERA\FULL STACK WEB DEVELOPMENT COURSE\CAPSTONE PROJECT\Capstone Project\watchours\node_modules\express\lib\router\index.js:271:10)

Your code has a few bugs/issues:

  1. You don't exit the function, when an error raised. Because of that, your code sends response twice: first one with error, second one with the data.
  2. You don't use promises. It's not a bug, but now it's 2017 and ES7 is already released, you should avoid using callbacks.

The fixed, improved code could looks so:

.put(Verify.verifyOrdinaryUser, (req, res, next) => {
    Episode
      .findById(req.params.episodeId, (err, episode) => {
        req.body.postedBy = req.decoded._id;

        episode.comments.id(req.params.commentId).remove();
        episode.comments.push(req.body);
        return episode.save();
    })
    .then(episode => res.send(episode))
    .catch(next);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM