首页 > 解决方案 > 一个中间件中的许多功能 expressjs restful api

问题描述

我对 express 中的 middelware 有疑问。

我想在一个中间件中进行多种思考。例如

我有这个代码和我的中间件

module.exports = function(req,res,next) {
    if(req.method === 'GET') {
        res.end('GET method not supported');
    } else {
        next();
    }
}; 

我像这样使用它

app.route('/', <the_middleware>, (res, req, next) => {
 // Code
})

但我想知道是否可以做这样的事情

app.route('/', <the_middleware>.<the function1>, (res, req, next) => {
     // Code
    })

app.route('/', <the_middleware>.<the_function2>, (res, req, next) => {
     // Code
    })

有没有可能做类似的事情

 function function1 (req,res,next) {
        if(req.method === 'GET') {
            res.end('GET method not supported');
        } else {
            next();
        }
    }; 

 function function2 (req,res,next) {
        if(req.method === 'GET') {
            res.end('GET method not supported');
        } else {
            next();
        }
    }; 

module.exports = <I don`t know what go here>

谢谢。

更新。它可以工作,我现在的代码是

路由器

router.post('/', checkAuth.sayHi, checkAuth.sayBye, (req, res, next) => {

    console.log('good');
    res.status(200).send('it works');
    console.log('yes');

});

中间件

module.exports = {

    sayHi(req, res, next) {
        console.log('hi');
        next();

    },

    sayBye(req, res, next) {
        console.log('bye')
        next();
    }
};

标签: node.jsexpress

解决方案


您可以只导出一个包含这两个函数的对象:

module.exports = {
  function1,
  function2
}

推荐阅读