添加方法req?

时间:2016-07-09 08:08:53

标签: node.js express

图书馆,例如快递验证和护照为req变量添加方法,如req.assertreq.user。我知道我可以从路线内做到这一点:

app.get('/', (req,res,next) => {
   req.foo = bar;
   next();
}

但是如何从库或外部模块中进行操作?

1 个答案:

答案 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())
// ...