gpt4 book ai didi

node.js - 向 req 添加方法?

转载 作者:太空宇宙 更新时间:2023-11-03 23:31:00 25 4
gpt4 key购买 nike

像express-validation和passport这样的库会向req-variable添加方法,例如req.assertreq.user。我知道我可以从路线内部执行此操作:

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

但是我如何从库或外部模块中做到这一点?

最佳答案

简而言之:您公开了一个处理程序函数,您的消费者将需要该函数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())
// ...

关于node.js - 向 req 添加方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38279779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com