我想知道是否有一种方法可以在 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) 并了解每个路由都是中间件。
此处常见的模式解决方案是向存储变量的 req
或 res
对象添加一个新属性。然后你告诉路由调用下一个中间件。下一个中间件可以访问相同的 req
和 res
,因此它也可以访问您刚刚存储的属性和值。
这种做法并没有错,因为大多数中间件都是这样做的。例如 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/