node.js - 一个中间件中的许多功能 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();
}
};
解决方案
您可以只导出一个包含这两个函数的对象:
module.exports = {
function1,
function2
}
推荐阅读
- java - 从 char 数组转换字符串时忽略尾随 NULL 字符
- r - RecordLinkage:更改分析单位,如何将去重数据集中的所有链接匹配导出到一行新数据框中?
- terraform - 有没有办法防止 Terraform google_container_cluster 在没有任何变化时被破坏和重新创建?
- java - 如何找到指定接入点的频段
- rest - 使用 Rest API 将文件上传到 Google Drive:无法设置名称
- javascript - 如何使用 React Native State 管理嵌套对象
- javascript - Vuex 在突变后无法更新组件
- neural-network - DarkNet - 没有检测到自定义训练数据
- swift - Firebase Default Parameters not logging to Events Dashboard
- c# - 如何将这两种方法结合起来?