app.use("/login", login);
app.use("*", (err: any, req: Request, res: Response, next: NextFunction) => {
console.log('errrorrrr')
res.send('ERRORRRRR4040404040404 ******')
});
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
console.log('errrorrrr')
res.send('ERRORRRRR4040404040404')
});
app.listen(config.port, () => {
console.log(`Running at port ${config.port}`);
});
I have set these two error handlers after the route. Instead of getting set res.send()
, I get Cannot GET /whynowork
on my browser with no console.log on my node.
How can I properly set the 404 Error
? I've tried just putting one of each but then it still returns Cannot GET /whynowork
and does not go through the error handlers.
CodePudding user response:
put this router after the last router you wrote, AND before the first error handling middleware (which expects err
as first param)
app.all('*', (req: Request, res: Response, next: NextFunction) => {
res.status(404).json({
message: 'hi its 404'
})
})
In the case you wrote above, this code should be between login
router and ERRORERROR...404 ******
router
app.use("/login", login);
app.all('*', (req: Request, res: Response, next: NextFunction) => {
res.status(404).json({
message: 'hi its 404'
})
})
app.use("*", (err: any, req: Request, res: Response, next: NextFunction) => {
console.log('errrorrrr')
res.send('ERRORRRRR4040404040404 ******')
});
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
console.log('errrorrrr')
res.send('ERRORRRRR4040404040404')
});
app.listen(config.port, () => {
console.log(`Running at port ${config.port}`);
});