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
相关产品推荐
相关产品推荐

