我设置了以下Express 4中间件堆栈: const app = express();const router = express.Router();router.get('/test', testResponse);app.use(checkAccessToken);app.use(router);app.use(sendResponse);//Error Handlingapp.use(function(err,req,r
const app = express(); const router = express.Router(); router.get('/test', testResponse); app.use(checkAccessToken); app.use(router); app.use(sendResponse); //Error Handling app.use(function(err,req,res,next) { // ... Do something here }); function sendResponse(req, res) { res.json({ data: res.locals.data, meta: res.locals.meta }); }
如果我使用不存在的路由(如GET / something)调用服务器,则在调用路由器处理程序之后调用sendResponse函数并且调用者获得标准响应而不是通常的消息“Can not GET / something”,来自最后的处理程序模块.
我认为应该调用错误处理程序,但事实并非如此.
有没有办法强制路由器在找不到路由时发出错误,或者如果路由未匹配则检查标准响应处理程序?
我知道我可以在res.locals中为任何匹配的路由添加一个值,并在标准响应处理程序中检查它,但我想用“正确”的方式来做,而不是使用一个变通方法.
var express = require('express'); var app = express(); app.use(require('body-parser').urlencoded({extended: false})); const router = express.Router(); router.use(function(req, res, next) { app.locals.test = 0; next(); }); router.get('/', function(req, res, next) { app.locals.test = 10; next(); }); router.get('/about', function(req, res, next) { app.locals.test = 20; next(); }); router.use(function(req, res, next) { if (!req.route) return next (new Error('404')); next(); }); router.use(function(err, req, res, next){ res.send(err.message); }) router.use(function(req, res){ res.send(app.locals.test + ''); }); app.use(router); app.listen(3000, function () { console.log('Example app listening on port 3000!'); });