Express中的404后备路由

3

我对Express的文档感到非常困惑。我想要实现一个非常简单的功能:为每个未匹配的路由返回自定义404页面。起初,这似乎非常直接:

app.get('/oembed', oembed()); // a valid route
app.get('/health', health()); // another one
app.get('*', notFound()); // catch everything else and return a 404

然而,当打开有效的URL(例如/oembed)时,express 仍然通过路由工作,并最终调用 notFound() 以及我仍然会看到/oembed响应,但控制台会显示错误,指出 在已发送正文的情况下,notFound() 正在尝试设置标头 (404)。 我尝试实现一个捕获此类错误的中间件
function notFound() {
  return (err, req, res, next) => {
    console.log(err);
    res.sendStatus(404);
    next(err);
  };
}

我已经使用了 app.use(notFound()); 添加了它,但是它甚至都没有被调用。我很难在互联网上找到任何关于这个问题的信息(例如不过时或错误的信息),而官方文档似乎也没有针对这个非常标准的用例提供任何具体的解释。我有点卡住了,不知道原因。


1
你的/oembed路由长什么样? - Vasil Dininski
1
我已经为实际中间件处理部分添加了注释。 - Lukas
2个回答

2
采用你的oembed实现:
export default () => function oembed(req, res, next) {
  const response = loadResponseByQuery(req.query);

  response.onLoad()
    .then(() => response.syncWithS3())
    .then(() => response.setHeaders(res)) // sets headers
    .then(() => response.sendBody(res))   // sends body
    .then(() => next())                   // next()

    .catch(() => response.sendError(res))
    .catch(() => next());
};

在发送响应正文后,它会调用 next,这意味着它将传播请求到任何后续(匹配的)路由处理程序,包括 notFound() 处理程序。

使用 Express 时,通常只有在当前处理程序无法响应请求,或者不知道如何处理请求,或者想要传递请求时才使用 next


谢谢,就是这个。 - Lukas

1
根据路由文档,我们可以使用正则表达式作为路径匹配器。
app.get(/.*/, (req, res) => {
  res.status(404).send();
  //res.json({ status: ":(" });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接