NodeJS Express-分别处理404(未找到)和405(不允许使用方法) [英] NodeJS Express - handling 404 (Not Found) and 405 (Method Not Allowed) separatedely

查看:790
本文介绍了NodeJS Express-分别处理404(未找到)和405(不允许使用方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到一种方法来处理我的Express应用程序中的404和405状态代码,但要分开处理它们.

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).')
)

但是,server.all方法将处理无效的路由或无效的HTTP动词.有没有一种方法可以分开对待它们,以便为每种情况发送不同的状态,内容和所有内容?

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?

谢谢大家!

推荐答案

我想到的第一件事是,在声明所有有用的路径后,为要响应的405路径声明每个错误. 例如,在您的accountRoutes中:

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');
});

如果您收到/account路径的get或post,它将被您的方法处理.其他方法将以405代码作为响应.

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.

未实现Express的路径会默认发送404代码,我认为您无需实现

Paths not implemented express will send a 404 code by default, I think you don't need to implement it

这篇关于NodeJS Express-分别处理404(未找到)和405(不允许使用方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆