gpt4 book ai didi

node.js - 沿 node-express 应用程序传递和更新数据

转载 作者:搜寻专家 更新时间:2023-10-31 23:50:18 24 4
gpt4 key购买 nike

如何在不使用 DB 的情况下通过 node-express 应用程序传递和更新数据。

所以我使用护照进行身份验证(考虑在 src/google-passport.js 中),

passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL,
userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
accessType: 'offline'
}, (accessToken, refreshToken, params, profile, cb) => {
let profileSort = extractProfile(profile)
mongooeHelperFunction.findUserByEmail(profileSort.email).then(response => {
if (!response) {
mongooeHelperFunction.createNewUser(profileSort)
.then(res => {
let newRes = {...res._doc}
newRes["accessToken"] = accessToken
cb(null, newRes)
})
.catch(error => { throw error })
} else {
let newRes = {...response._doc}
newRes["accessToken"] = accessToken
cb(null, newRes)
}
})
.catch(error => { throw error })
}
))

我从 Passport 获得了一个访问 token 和刷新 token 。通常谷歌访问 token 的有效期为一个小时。

所以我想存储我收到访问 token 的时间,如果我的访问 token 已过期,我想使用刷新 token 来获取新的访问 token ,然后在生成新的访问 token 后更新时间。

考虑一个api路由

app.get("/something", isTokenValid, (req, res) => {

其中 isTokenValid 是一个中间件函数,在该函数中,我可以在何时 创建我的护照 token ,然后我可以将它与当前时间进行比较。

此外,如果 token 已过期,我有一个函数可以发送刷新 token 以获取新的访问 token 并将访问 token 的先前数据/时间更新为新的日期/时间

问题:如何通过 node-express 应用传递和更新数据

最佳答案

创建上下文对象

在您的示例中,我们添加了另一个为中间件管道创建上下文的中间件:

const initCtx = (req,res,next) => {
req.ctx = {};
next();
}

然后在你的中间件声明中:

    app.get("/something", [initCtx, isTokenValid], (req, res) => {

通常这可以作为管道中的第一个中间件完成,在整个应用程序的中间件声明顶部:

const initCtx = (req,res,next) => {
req.ctx = {};
next();
}
app.use(initCtx);

将值传递到 ctx

isTokenValid 中间件中,您可以在其中检索 accessToken 及其过期时间,在它结束时您可以通过它。其中访问 token 到期时间为 tokenExpiration:

req.ctx.tokenExpiration = tokenExpiration;

使用值(value)

在负责刷新 token 的中间件中:

 app.get("/something", [initCtx, isTokenValid], (req, res) => {
const tokenExpiration = req.ctx.tokenExpiration; // you have token expiration time that you can compare and apply required logic in refreshing token middleware

原回复及说明

您可以分配属性 ctx(上下文对象)来表达 req 对象并通过它在中间件之间传递信息。然后您将能够在下游中间件中检查此对象中的特定键并应用所需的逻辑。

ctx 对象可以由管道中的第一个中间件创建(这个中间件通常还检查 header 中的 requestId 并将其分配给 ctx 作为好吧,所以可以很容易地跟踪同一请求上下文中的所有操作)

如果token有效你可以分配req.ctx.tokenExpiration,然后在另一个中间件检查是否需要刷新它。

顺便说一句,Koa 和 Loopback 框架开箱即用地使用 ctx 对象。

关于node.js - 沿 node-express 应用程序传递和更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53984290/

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