I'm trying to find a way to handle both 404 and 405 status code in my Express application, but handling them separatedely.
e.g.: I have a router like the following:
// Add routes for every path we define here.
server.use('/', require('./indexRoutes'))
server.use('/account', require('./accountRoutes'))
// Handling route errors.
server.all('*', (request, response) =>
response.status(404).send('Invalid route (not found).')
)
However, either invalid routes or invalid HTTP verbs are being treated by the server.all
method. Is there a way to treat them separatedely, in order to send different status, content and everything for each scenario?
Thank y'all!
First thing that come to my mind is to declare for each path you want to response 405 error after you declare all your useful paths. For example, in your accountRoutes:
server.get('/account', ....);
server.post('/account', ...);
server.all('/account', (req, res, next) => {
res.status(405).send('Method not allowed');
});
If you receive a get or post to the /account path it will be treated with your method. Other methods will be responded with 405 code.
Paths not implemented express will send a 404 code by default, I think you don't need to implement it