Node.js 404快车后备路线

Node.js 404快车后备路线,node.js,express,error-handling,routing,Node.js,Express,Error Handling,Routing,我完全被Express看似糟糕的文档弄糊涂了。我想归档一件非常简单的事情:在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 但是,当一个有效的

我完全被Express看似糟糕的文档弄糊涂了。我想归档一件非常简单的事情:在
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()),但它甚至不会被调用。我发现在互联网上很难找到这方面的任何东西(例如,没有过时或错误),官方文档似乎没有针对这个非常标准的用例的任何特定内容。我有点被困在这里,我不知道为什么。

将您的
实现嵌入其中:

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
通常仅用于在当前处理程序不响应请求,或者不知道如何或不想处理请求的情况下传递请求。

根据

app.get(/.*/,(req,res)=>{
res.status(404.send();
//res.json({状态::(“});
});

您的
/oembed
路线是什么样子的?我对实际中间件发生的代码进行了注释谢谢,就是这个。