Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js Routing error: Can't set headers after they are sent

I'm not really sure why I'm getting this error. It's a simple API built on express.js to be able to add and remove posts. The error occurs when I trigger the delete router. I've read that the error typically happens when there are two callbacks, however, I don't seem to be able find any double callbacks.

    _http_outgoing.js:344     throw new Error('Can\'t set headers after they are sent.');     Error: Can't set headers after they are sent.     at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)     at ServerResponse.header (/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:718:10) at ServerResponse.send (/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:163:12)     at ServerResponse.json (/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:249:15)     at /Users/bounty/Projects/_learning/react-express/server/routes/posts.js:86:9     at nextTickCallbackWith0Args (node.js:452:9)     at process._tickCallback (node.js:381:13) 

Here is my posts.js router:

module.exports = function(router) {      var Post = require('../models/post.js');      // middleware for the api requests     router.use(function(req, res, next) {         // do logging         console.log('something is happening.');         next(); // make sure we go to our next route and don't stop here     });      // test route to make sure everything is working (accessed at GET http://localhost:8080/api)      router.get('/', function(req, res) {         res.json({ message: 'hooray! welcome to our api!' });        });      // all routes here      // routes that end in /posts     router.route('/posts')          // create a Post (accessed at POST http://localhost:7777/api/posts)         .post(function(req, res) {             var post = new Post();             post.postTitle = req.body.postTitle; // set the post name (comes from request)               // save post and check for errors             post.save(function(err) {                 if (err)                     res.send();                  res.json({ message: 'post created!' });             });         })          // get all Posts (accessed at GET http://localhost:7777/api/posts)         .get(function(req, res) {             Post.find(function(err, posts) {                 if (err)                     res.send();                  res.json(posts);             });         });      // routes that end in /posts for specific id     router.route('/posts/:post_id')          // get the post with that id         .get(function(req, res) {             Post.findById(req.params.post_id, function(err, post) {                 if (err)                     res.send(err);                  res.json(post);             });         })          // update the post with that id         .put(function(req, res) {             Post.findById(req.params.post_id, function(err, post) {                 if (err)                     res.send(err);                  post.postTitle = req.body.postTitle;                  // save the post                 post.save(function(err) {                     if (err)                         res.send(err);                      res.json({ message: 'post updated!' });                 });             });         })          // deletes the post with that id         .delete(function(req, res) {             Post.remove({                 _id: req.params.post_id             }, function(err, post) {                 if (err) {                     res.send(err);                 }                 res.json({ message: 'post deleted!' });             });         }); } 
like image 734
bounty Avatar asked Jan 25 '16 00:01

bounty


People also ask

Can't set headers after they are sent?

The error "Error: Can't set headers after they are sent." means that you're already in the Body or Finished state, but some function tried to set a header or statusCode. When you see this error, try to look for anything that tries to send a header after some of the body has already been written.

How do you fix error Err_http_headers_sent ]: Cannot set headers after they are sent to the client?

To Solve Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client Here You Need To use return statement to solve this error. Error Is occurs Because Of Your res. status(400). json is executing and then your function is not going to stop.

What is setHeader in node JS?

setHeader(name, value) (Added in v0. 4.0) method is an inbuilt application programming interface of the 'http' module which sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced.

Does Res send end the function?

send doesn't return the function, but does close the connection / end the request.


Video Answer


1 Answers

You need to add the 'return' so that you don't reply twice.

// save post and check for errors post.save(function(err) {     if (err) {         return res.send();     }     res.json({ message: 'post created!' }); }); 
like image 78
Gadi Avatar answered Oct 22 '22 15:10

Gadi