For some reason, if I'm the last piece of middleware and I try calling the next()
function, I get the same error as this common SO issue.
So that I have a minimal example, I set it up as follows:
In my route, I have:
router.get('/add',(req,res,next) => {
res.render('ideas/add');
next();
});
And then I have a final piece of middleware:
app.use(function finalMiddleware(req,res,next){
console.log("We are here!");
console.log(app._router.stack);
next();
});
And the console logs the following as the last element in the stack:
Layer {
handle: [Function: finalMiddleware],
name: 'finalMiddleware',
params: {},
path: '',
keys: [],
regexp: { /^\/?(?=\/|$)/i fast_star: false, fast_slash: true },
route: undefined } ]
However, I still get:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:471:11)
at ServerResponse.header (../node_modules/express/lib/response.js:767:10)
at ServerResponse.send (../node_modules/express/lib/response.js:170:12)
at done (../node_modules/express/lib/response.js:1004:10)
at Immediate.<anonymous> (../node_modules/express-handlebars/lib/utils.js:26:13)
I'm wondering if this for some reason has to do with handlebars? I just don't understand why if I'm not writing headers with later middleware that this would possibly be an issue. I can't seem to figure out how to debug it further. Sure, I can remove the next()
call from my final piece of middleware, but I want to understand if there's something deeper going on as I'm new to Express and want to make I'm understanding stuff correctly.