NodeJS Express - handling 404 (Not Found) and 405 (Method Not Allowed) separatedely

末鹿安然 提交于 2019-12-11 12:58:15

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/47776160/nodejs-express-handling-404-not-found-and-405-method-not-allowed-separated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!