图书馆,例如快递验证和护照为req变量添加方法,如req.assert
和req.user
。我知道我可以从路线内做到这一点:
app.get('/', (req,res,next) => {
req.foo = bar;
next();
}
但是如何从库或外部模块中进行操作?
答案 0 :(得分:2)
简而言之:您公开了消费者需要的处理程序功能app.use()
。
这是一般方法。请考虑以下模块:
module.exports = function myExtension() {
return function myExtensionHandler(req, res, next) {
// This is called for every request - you can extend req or res here
req.myFun = myFun
// Make sure to call next() in order to continue the
// chain of handlers
return next()
}
}
function myFun() {
// My magic function
}
现在,从消费者的角度来看:
const express = require('express')
const myExtension = require('my-extension')
const app = express()
// Here you tell Express to use your extension for incoming requests
app.use(myExtension())
// ...