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

Express框架如何获取另一文件中app.use内部定义的变量值

问题根因
  • 模块执行时机错误:json/chatbot.js 内的代码会在首次被 require 时一次性执行完成,此时请求还未触发,app.use 回调内的局部变量 bot、client 根本不存在
  • 局部变量无法跨文件直接访问:bot 是 app.use 回调内部的局部变量,不会挂载到导出的 Router 实例上,你写的 botFile.app.bot 本身就不可能拿到有效值
  • 存在循环引用:chatbot.js 和 json/chatbot.js 互相引用,也会导致变量获取异常
  • 动态参数错误:bot、client 是每个请求携带的动态query参数,不能在模块初始化阶段就写入静态JSON中,必须在每次请求时动态传入生成内容
修复方案

把静态JSON导出改为导出工厂函数,每次请求时传入当前的bot、client参数动态生成返回内容即可。

修改 json/chatbot.js

// 导出工厂函数,接收动态的bot和client参数
module.exports = (bot, client) => {
  const data1 = ["Hi!", "Yo!", "Wassup", `Hello ${client}`]
  const rep1 = data1[Math.round(Math.random() * data1.length)]
  return {
    "result": {
      "hi": {
        "reply": rep1,
        "id": 0
      },
      "hello": {
        "reply": rep1,
        "id": 0
      },
      "sup": {
        "reply": rep1,
        "id": 0
      },
      "yo": {
        "reply": rep1 ,
        "id": 0
      },
      "who are you": {
        "reply": `I'am ${bot}`,
        "id": 1
      }
    }
  }
}

修改 chatbot.js

const express = require('express');
const app = express.Router();
// 提前引入工厂函数,不要放在请求回调内重复加载
const getChatbotJson = require('./json/chatbot')

app.use(['/chat', '/chatbot'], (req, res, next) => {
  const bot = req.query.bot;
  const client = req.query.client;
  const text = req.query.text;
  // 传入当前请求的动态参数,生成对应配置
  const json = getChatbotJson(bot, client);
  // 加兜底避免请求不存在的text参数时报错
  const result = json.result[text]?.reply || 'Unknown command';
  console.log(result);
  res.json({'reply': result});
});

module.exports = app;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:18:02