如何捕获在 Express 路由器中找不到的页面

How to catch page not found in express router

我想在 express 路由器中捕获 404 页面未找到 错误。

我用一个基本的例子:

const express = require('express');

const app = express();

const router = express.Router();

// ROUTER MID BEFORE
router.use((req, res, next) => {console.log("Router Mid => Before"); next();});

// ROUTER PAGE /BAR
router.get('/bar', (req, res, next) => {
 console.log("Router page '/bar'");
 res.send('<body><h1>Hello World</h1></body>');
 next();
 }); 

// ROUTER NOT FOUND
router.get('*', (req, res, next) => {console.log("Router NOT FOUND"); next();});

// ROUTER MID AFTER
router.use((req, res, next) => {console.log("Router Mid => After"); next();});

// APP MID BEFORE
app.use((req, res, next) => {console.log("----"); console.log("App Mid => Before"); next();});

app.use('/foo', router);

// APP NOT FOUND
app.get('*', (req, res, next) => {console.log("App NOT FOUND"); next();});

// APP MID AFTER
app.use((req, res, next) => {console.log("App Mid => After"); console.log("----"); next();});

app.listen(3000, () => {console.log("App Listenning")});

我希望得到以下结果:

请求/任何

----
App Mid => Before
App NOT FOUND
App Mid => After
----

请求 /foo/anything

----
App Mid => Before
Router Mid => Before
Router NOT FOUND
Router Mid => After
App Mid => After
----

请求 /foo/bar

----
App Mid => Before
Router Mid => Before
Router page '/bar'
Router Mid => After
App Mid => After
----

但是 Not Found 页面在每次请求时都会执行

例如请求 /foo/bar 给我:

----
App Mid => Before
Router Mid => Before
Router page '/bar'
Router NOT FOUND
Router Mid => After
App NOT FOUND
App Mid => After
----

我怎样才能做到这一点?

我发现实现这一目标的唯一方法是在所有中间件中传递自定义标志。 这样我就可以知道路由是否已经发送了响应或者我是否需要发送找不到的页面。

const express = require('express');
const app = express();
const router = express.Router();

// Custom not found flag setup
app.use((req, res, next) => {req.pageFound = false; next();});

// ROUTER MID BEFORE
router.use((req, res, next) => {console.log("Router Mid => Before"); next();});

// ROUTER PAGE /BAR
router.get('/bar', (req, res, next) => {
 req.pageFound = true;
 console.log("Router page '/bar'");
 res.send('<body><h1>Hello World</h1></body>');
 next();
}); 

// ROUTER NOT FOUND
router.get('*', (req, res, next) => {
 if (req.pageFound === false) { 
  req.pageFound = true;
  console.log("Router NOT FOUND");
  next();
}});

// ROUTER MID AFTER
router.use((req, res, next) => {console.log("Router Mid => After"); next();});

// APP MID BEFORE
app.use((req, res, next) => {console.log("----"); console.log("App Mid => Before"); next();});

app.use('/foo', router);

// APP NOT FOUND
app.get('*', (req, res, next) => {
if (req.pageFound === false) {
 req.pageFound = true;
 console.log("App NOT FOUND");
 next();
}});

// APP MID AFTER
app.use((req, res, next) => {console.log("App Mid => After"); console.log("----"); next();});

app.listen(3000, () => {console.log("App Listenning")});