如何检查ExpressJS服务器如果请求路径不存在(404)或不?



我们从随机机器人在互联网上爬行的请求不时地用随机路径发送垃圾请求,我们想要过滤掉404请求被记录在我们的服务器上。问题是,即使路径存在,当参数指向不存在的资源时,我们的一些请求处理程序故意将响应的状态码设置为404,这使得我们无法在中间件中不存在请求路径时使用状态码作为指示符。是否有一种方法可以检查请求的路径是否确实不存在,而不依赖于响应的状态码?

app.use(
morgan('combine', {
skip(req, res) {
if (res.statusCode == 404) return true; // any alternatives to this?
if (res.statusCode < 400) return true;
return false;
}
})
)

在不依赖于响应状态码的情况下过滤404请求的另一种方法是使用一个单独的中间件来检查所请求的路径是否存在于您的应用程序中。

app.use((req, res, next) => {
// match the path to your router
const pathMatch = app._router.stack.find(layer => layer.regexp.test(req.path));
if (pathMatch) {
// If the requested path exists, continue with the request handling
next();
} else {
// If the requested path does not exists
}
});

最新更新