Express中的404后备路线

我完全被Express看似不好的文档弄糊涂了。 我想存档一个非常简单的事情:返回一个自定义404为每个不匹配的路线在express 。 起初,这看起来很直截了当:

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

但是,当一个有效的URL被打开(像/oembedexpress继续通过路由工作,并最终调用notFound() 以及 。 我仍然可以看到我的/oembed响应,但是在控制台中出现错误,说已经发送正文时, notFound()试图设置标题( 404 )。

我试图实现一个捕获像这样的错误的中间件

 function notFound() { return (err, req, res, next) => { console.log(err); res.sendStatus(404); next(err); }; } 

并添加app.use(notFound()); ,但这甚至不会被调用。 我发现很难在互联网上find任何东西(例如,这不是过时的或错误的),官方文档似乎没有任何具体的这个非常标准的用例。 我有点卡在这里,我不知道为什么。

采取您的实施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()); }; 

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

使用Express, next通常只用于传递一个请求,如果当前处理程序没有响应,或者不知道如何处理或者不想处理。