找不到路由时Express 4中间件(finalhandler未调用):如何检查? [英] Express 4 middleware when route is not found (finalhandler not called): how to check for it?

查看:136
本文介绍了找不到路由时Express 4中间件(finalhandler未调用):如何检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了以下Express 4中间件堆栈:

I set up the following Express 4 middleware stack:

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),则在调用路由器处理程序并且调用者获得标准响应而不是通常的消息"Cannot GET/something"后立即发送sendResponse函数,来自finalhandler模​​块.
相反,我认为应该调用错误处理程序,但事实并非如此.
如果找不到路由,是否有办法强制路由器发出错误,或者如果路由未匹配,是否有办法签入标准响应处理程序?
我知道我可以在任何具有匹配项的路由中在res.locals中添加一个值,并在标准响应处理程序中进行检查,但是我想使用正确"的方法来进行操作,而不是使用变通方法

If I call the server with a route that doesn't exist (like GET /something) the function sendResponse just after the router handler is called and the caller gets a standard response instead of the usual message "Cannot GET /something", coming from the finalhandler module.
I thought instead that the error handler should have been called, but this is not the case.
Is there a way to force the router to emit an error if a route is not found or to check in the standard response handler if a route has not been matched?
I know that I can add a value in res.locals for any route that has a match and check for it in the standard response handler, but I'd like to use the "right" way to do it, rather than using a workaround.

推荐答案

您可以检查req.route.

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!');
});

这篇关于找不到路由时Express 4中间件(finalhandler未调用):如何检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆