Express路由器绕过中间件

时间:2018-07-10 15:57:59

标签: node.js express

我正在尝试创建中间件来处理路由中next()发出的响应,但是它绕过route.use并抛出404

const router = require('express').Router();
const { errorResponse, successResponse, redirectResponse } = require('./test');

const errorResponse = (err, req, res, next) => {
    next(Boom.notFound());
};

const successResponse = (err, req, res, next) => {
    res.locals.res = {
        data: {
            hello: 'world'
        }
    };
    next();
};

const redirectResponse = (err, req, res, next) => {
    res.locals.res = {
        meta: {
            redirect: true
        }
    };
    next();
};

module.exports = (app) => {
    /**
     * Test Routes
     */
    router.get('/successTest', successResponse);
    router.get('/errorTest', errorResponse);
    router.get('/redirectTest', redirectResponse);

    router
        .use((err, req, res, next) => {
            console.log('successHandler');
            next();
        })
        .use((err, req, res, next) => {
            console.log('redirectHandler');
            next();
        })
        .use((err, req, res, next) => {
            console.log('errorHandler');
            res.status(200).json({});
        });
        // does not go to any of the middlewares and gives out 404
        // from digging in i found that err param is not err but is req
    app.use('/v1', router);
};

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

看看Express.js错误处理中间件documentation

基本上,它说带有4个参数的中间件,例如

app.use(function (err, req, res, next) {
 console.error(err.stack)
 res.status(500).send('Something broke!')
})

被解释为用于处理错误的中间件。 这意味着它不会像常规中间件那样起作用。

例如:

app.get('/1',
  (err, req, res, next) => {
    // will not be outputted in console
    console.log('got here');
    next();
  },
  (req, res) => {
    res.send('Hello World!');
  });
app.get('/2',
  (req, res, next) => {
    console.log('got here');
    next();
  },
  (req, res) => {
    res.send('Hello World!');
  });