正如@HeadCode 提到的,一定要阅读meddleware 以了解如何更好地加载中间件。
也就是说,我们必须回顾一些事情才能使正在发生的事情更加清晰。
处理 404s
首先,让我们回顾一下通常如何在普通的旧 express 应用中注册 404 处理程序。
通常,您的中间件延续链中有最终的中间件,只是假设,如果我们在没有放弃的情况下做到了那么远,我们根本找不到资源。这是一个例子:
var express = require('express');
var app = express();
app.get('/firstRoute', function handler(req, res) { res.send('found me'); });
app.get('/secondRoute', function handler(req, res) { res.send('found me'); });
app.use(function notFoundHandler(req, res, next) {
res.status(404).send('Route Not Found');
});
app.listen(8000, function onListen() { console.log('listening on 8000...'); });
由于routes are resolved in the order they're added in Express 4,只要您的 404 处理程序是最后一个,您就可以确定没有其他路由匹配。
Express FAQs 中简要描述了这种模式。
处理 500s
现在让我们转到 500 秒。
Express 具有错误处理中间件的概念(在Express site 中也有描述)。错误处理中间件需要 4 个参数(即,需要四个参数),这是唯一的区别。只有在发出错误信号时才会执行它们,这是通过将对象传递给您的 next 调用来完成的。在代码中更容易解释:
var express = require('express');
var app = express();
app.get('/firstRoute', function handler(req, res) { res.send('found me'); });
app.get('/secondRoute', function handler(req, res) { throw new Error('oops'); });
app.use(function notFoundHandler(req, res, next) {
res.status(404).send('Route Not Found');
});
app.use(function errorHandler(err, req, res, next) {
res.status(500).send('Broken. :(');
});
app.listen(8000, function onListen() { console.log('listening on 8000...'); });
在上面的例子中,errorHandler 只会在 1) 另一个中间件或路由处理程序抛出错误或 2) 我们使用参数 * 调用 next 时才会执行,例如next(new Error('oops')).
继续运行它。如果您访问/notFound 或任何随机路线,您将正确获得404。如果您访问/firstRoute,您将获得found me,如果您访问secondRoute,您将获得Broken. :(。
海妖呢?
Kraken——或者更准确地说,meddleware——只是将你的中间件定义移动到你的配置中。您在上面复制的那一小段 json 在功能上基本上等同于 vanilla express 应用程序中的以下内容:
var fileNotFound = require('./lib/exceptions/404');
// ... app.use() everything with a priority lower than 130 ...
app.use(fileNotFound());
// ... app.use() everything with a priority *greater* than 130 ...