You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何在不同路由之间共享使用同一变量

问题原因

你在app.post('/post')的回调函数内部用var test定义的变量属于函数局部作用域变量,仅在当前回调函数内部可访问,外部路由无法直接读取。且express路由回调的return值不会被外部捕获,所以你写的return test没有实际作用。


解决方案

根据使用场景不同可以选择以下三种方案:

场景1:test是用户级变量,不同用户提交的test需要隔离使用

这是绝大多数业务场景的最优选择,推荐用express-session存储用户级变量:

  1. 安装依赖
npm install express-session
  1. 初始化session(代码写在路由定义之前)
const session = require('express-session');
app.use(session({
  secret: '自定义加密字符串',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false } // 生产环境走https可改为true
}))
  1. 改造post路由
app.post('/post', function(req, res){
    const test = req.body.test
    // 存入当前用户专属session
    req.session.test = test
    res.render('folder/ejs.ejs', { test: test })
})
  1. 改造get路由
app.get('/get', function(req, res) {
    // 先判空避免非法请求报错
    if (!req.session.test) {
      return res.status(400).send('请先提交test参数')
    }
    axios.get('https://www.randomletters.com/1234/' + req.session.test)
    .then((response)=>{
    // 后续业务逻辑
})

场景2:test是全局公共变量,所有用户共享同一个值

直接在路由外层的全局作用域定义变量即可,注意这种方式下新的/post请求会覆盖之前的test值,仅适合全局配置类变量使用:

// 定义在所有路由外层
let globalTest = ''

app.post('/post', function(req, res){
    const test = req.body.test
    globalTest = test
    res.render('folder/ejs.ejs', { test: test })
})

app.get('/get', function(req, res) {
    axios.get('https://www.randomletters.com/1234/' + globalTest)
    .then((response)=>{
    // 后续业务逻辑
})

场景3:不需要后端存储,前端请求时自行携带test

你在/post返回的ejs模板里已经把test传给前端了,可以把test存在前端localStorage、cookie或者url参数里,调用/get接口时作为查询参数传给后端:
前端请求示例:

fetch('/get?test=' + 前端存储的test值)

后端get路由接收:

app.get('/get', function(req, res) {
    const test = req.query.test
    axios.get('https://www.randomletters.com/1234/' + test)
    .then((response)=>{
    // 后续业务逻辑
})

内容的提问来源于stack exchange,提问作者PythonIs2Hard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:24:03