node.js - 在 2 条路线 express 之间共享一个变量

标签 node.js express

我想知道是否有一种方法可以在 expressJS 中的 2 条路由之间共享变量,而无需将其声明为全局变量。假设我有以下路线:

exports.routeOne = (req,res) => { 
 var myVariable='this is the variable to be shared';
}

exports.routeTwo = (req,res) => {
  //need to access myVariable here
}

如何做到这一点?

最佳答案

===============

注意

这个答案回答了错误的问题,但它可能对其他像我一样误解了这个问题的人仍然有用,所以我暂时把它放在这里。

===============

为了使变量存在,它必须首先执行 routeOne,然后执行 routeTwo。这是 express 很常见的场景。要了解其工作原理的详细信息,请阅读中间件 (http://expressjs.com/en/guide/writing-middleware.html) 并了解每个路由都是中间件。

此处常见的模式解决方案是向存储变量的 reqres 对象添加一个新属性。然后你告诉路由调用下一个中间件。下一个中间件可以访问相同的 reqres,因此它也可以访问您刚刚存储的属性和值。

这种做法并没有错,因为大多数中间件都是这样做的。例如 body-parser 中间件 ( https://www.npmjs.com/package/body-parser )。

这是您的代码可能如何运行的示例:

routes.js

exports.routeOne = (req,res,next) => { 
 req.myVariable='this is the variable to be shared'
 next()
}

exports.routeTwo = (req,res) => {
  //need to access myVariable here
  console.log(req.myVariable)
}

index.js

const express = require('express')
const routes = require('./routes.js)

const app = express()
app.use(routes.routeOne)
app.use(routes.routeTwo)

app.listen(3000)

关于node.js - 在 2 条路线 express 之间共享一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957344/

相关文章:

node.js - Webpack 如何使用 Target 属性

node.js - mongodb 连接错误导致 kubernetes pod 挂起并重新启动 pod 修复该问题

javascript - 如何让node js express服务器并行处理请求

node.js - 如何在 Node.js 和 Express 中以嵌套形式呈现多个 .ejs 文件?

node.js - Three.js 与 typescript 自动完成

node.js - AWS Lambda 函数子目录中的处理程序未运行

javascript - 在页面加载时将正斜杠附加到 url 的末尾

javascript - 蒙戈 : Update value of string array element using the element itself

node.js - Passport-facebook Node 应用程序不起作用

javascript - 如何检查浏览器中是否存在同名的cookie,并据此对特定页面进行授权