【问题标题】:Send variables to all routes in expressjs将变量发送到 expressjs 中的所有路由
【发布时间】:2022-01-08 22:00:37
【问题描述】:

我在登录时设置了req.session 变量,如下所示:

req.session.loggedin = true
req.session.firstname = loginDetails.firstName;

我想要做的是将此信息传递给所有路线(我有将近 60 条,并且不想遍历所有路线并手动添加这些),而且我拥有的每条路线都调用前端使用这个:

res.render('page.ejs', {data: rows}), so I would ideally want it to pass it to the front-end pages so I can access them there too. Not sure if this is possible, but worth a shot! thx 4 the help in advance!

【问题讨论】:

标签: javascript node.js express ejs


【解决方案1】:

您可以创建一个中间件函数并将变量添加到现有的express-session

app.js

const express = require("express");
const session = require("express-session");

// express app
const app = express();
app.use(express.json());

// init example session with express session
app.use(session({ resave: true, secret: "123456", saveUninitialized: true }));

// use a middleware function
app.use((req, res, next) => {
  if (!req.session.initialised) {
    // init variables you want to set in req.session
    req.session.loggedin = true;
    req.session.firstname = "john doe";
  }
  next();
});

// test api endpoint
app.use("/testroute", require("./routes/api/test"));

// run server
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

然后您可以在请求对象的任何其他路由中查询您的变量,例如req.session.firstname。你也可以从你的路线更新它

test.js

// testroute
const router = express.Router();

router.get("/", async (req, res) => {
  // get variables from request object
  try {
    console.log(req.session.firstname);
    console.log(req.session.loggedin);

    // this would update the session variable if uncommented
    // req.session.firstname = "dagobert"
    // console.log(req.session.firstname);
    res.status(200).json({ message: `Your firstname is ${req.session.firstname}` });
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

module.exports = router;

【讨论】:

    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    相关资源
    最近更新 更多