**app.get('/', (req,res)=>{
res.send('Api is running...');
})
app.use('/api/products/', productRoutes);
app.use(notFound);
app.use(errorHandler);**
Above is the gist of my code where app.use(notFound) and app.use(errorHandler) are middleware. This pattern works perfectly fine. However when i interchange the position of the command to below then there is a break in the application. are middlewares to be placed at the bottom? please help me here to clear my confusion.
**app.get('/', (req,res)=>{
res.send('Api is running...');
})
app.use(notFound);
app.use(errorHandler);
app.use('/api/products/', productRoutes);**
Actually, yeah, I suggest notFound
middleware sends the response and set headers, so that calling errorHandler
or productRoutes
leads to common error Cannot set headers after they are sent
. If you define middlewares before routes — they are called first(I personally name them as 'configurable middlewares' or 'middlewares that configure my express app').
But if you define them after routes they will be called by next()
function which is provided by a 'route'. next()
calls the next middleware 'in a queue' after routes.