Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 通过node express应用程序传递和更新数据_Node.js_Express - Fatal编程技术网

Node.js 通过node express应用程序传递和更新数据

Node.js 通过node express应用程序传递和更新数据,node.js,express,Node.js,Express,如何在不使用DB的情况下沿node express应用程序传递和更新数据 因此,我使用passport进行身份验证(将其视为src/google passport.js) 从Passport中,我获得一个访问令牌和刷新令牌。通常谷歌访问令牌的有效期为一小时 因此,我想存储接收访问令牌的时间,如果访问令牌过期,我想使用刷新令牌获取新的访问令牌,然后在生成新的访问令牌后更新时间 考虑一个api路由 app.get("/something", isTokenValid, (req, res) =>

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

因此,我使用passport进行身份验证(将其视为src/google passport.js

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

因此,我想存储接收访问令牌的时间,如果访问令牌过期,我想使用刷新令牌获取新的访问令牌,然后在生成新的访问令牌后更新时间

考虑一个api路由

app.get("/something", isTokenValid, (req, res) => {
其中,
isTokenValid
是一个中间件函数,在该函数中,我可以在创建我的passport令牌时使用,然后我可以将其与当前时间进行比较

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

问题:如何沿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
,以及它的过期时间,在它的末尾,您可以传递它。其中,访问令牌到期为
令牌到期

req.ctx.tokenExpiration=tokenExpiration

使用价值 在负责刷新令牌的中间件中:

 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
对象可以由管道中的第一个中间件创建(该中间件还经常检查头中的
requestId
,并将其分配给
ctx
,因此可以轻松跟踪同一请求上下文中的所有操作)

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


顺便说一下,Koa和环回框架与CTX对象一起工作了。< /P>我可以通过这样做来创建CTX吗?code>res.ctx=date.now在我的express应用程序中?最好在管道
应用程序中的其他第一个中间件中创建ctx。使用((req,res,next)=>{req.ctx={};next();})。我还更正了我的答案-最好使用
req.ctx
。然后您需要在
isTokenValid
中间件中分配:
req.ctx.tokenExpired
。是的,您只需为每个请求创建
ctx
对象,将其分配给请求,然后您就可以在所有中间件管道中首先填充、检查和使用其中的属性!非常感谢你的回答。请你在回答中添加更多细节好吗?(如包含文本中的上下文)。由于某种原因,我无法理解如何从您的回答中理解:谢谢,请这样做:)我进行了重构,并提供了更详细的答案。希望有帮助:)
 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