Search code examples
node.jsreactjsmongodbmongoosemern

ErrorCaptureStackTrace(err); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client


const seedRouter = express.Router();

seedRouter.get('/', async (req, res) => {
  await Product.remove({});
  const createdProducts = await Product.insertMany(Data.products);
  res.send({ createdProducts });

  await User.remove({});
  const createdUsers = await User.insertMany(Data.users);
  res.send({ createdProducts, createdUsers });
});

export default seedRouter;
node:internal/errors:484
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:393:5)
    at ServerResponse.setHeader (node:_http_outgoing:644:11)
    at ServerResponse.header (F:\Laxman website\E-commerce\backend\node_modules\express\lib\response.js:794:10)
    at ServerResponse.send (F:\Laxman website\E-commerce\backend\node_modules\express\lib\response.js:174:12) 
    at ServerResponse.json (F:\Laxman website\E-commerce\backend\node_modules\express\lib\response.js:278:15) 
    at ServerResponse.send (F:\Laxman website\E-commerce\backend\node_modules\express\lib\response.js:162:21) 
    at file:///F:/Laxman%20website/E-commerce/backend/routes/seedRoutes.js:15:7
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

app is crashed and it returns with the error above 'Cannot set headers after they are sent to the client'. Thank you.


Solution

  • This particular error is caused by trying to send more than one response to the same request. In your particular case, you are calling res.send() twice in the same request. You can't do that as res.send() ends the request.

    We don't know what you're trying to accomplish in your request handler, but it appears you can just remove the first res.send({ createdProducts }); since you're already sending that data in the second one.

    You also need a try/catch around your await so you catch promise rejections and can send an error response.

    seedRouter.get('/', async (req, res) => {
      try {
          await Product.remove({});
          const createdProducts = await Product.insertMany(Data.products);
    
          await User.remove({});
          const createdUsers = await User.insertMany(Data.users);
          res.send({ createdProducts, createdUsers });
     } catch(e) {
          console.log(e);
          res.sendStatus(500);
     }
    });