【发布时间】:2021-10-10 06:46:41
【问题描述】:
如果变量在 app.use 中,如何获取变量值
聊天机器人.js:
const express = require('express');
const app = express.Router();
app.use(['/chat', '/chatbot'], (req, res, next) => {
const bot = req.query.bot;
const client = req.query.client;
const text = req.query.text;
const json = require('./json/chatbot')
const result = JSON.parse(JSON.stringify(json.result[req.query.text].reply));
console.log(result)
res.json({'reply': result});
});
module.exports = app;
json/chatbot.js:
const botFile = require('../chatbot');
const bot = botFile.app.bot;
const data1 = ["Hi!", "Yo!", "Wassup", `Hello ${client}`]
const rep1 = data1[Math.round(Math.random() * data1.length)]
const json = {
"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
}
}}
module.exports = json;
使用的网址:
https://api.domain.repl.co/api/v1/chat?client=ClientTEST&bot=Chat+Bot&text=who+are+you
应该回复
{"reply": "I'am Chat Bot"}
但它却回复了
{"reply": "I'am undefined"}
控制台没有错误
【问题讨论】:
-
第 9 行的 require 后“json”的值是多少?
-
const bot = botFile.app.bot; // 这可能是未定义的
-
如果我做 const bot = require('../chatbot') 它将变成 app.use(['/chat', '/chatbot'], ...
-
但如果我执行 const { bot } = require('../chatbot'),它也会变得未定义
-
你这里有一个循环依赖。如果没有像 webpack 这样的构建工具来为你解决冲突,你就不能互相要求两个文件。
标签: javascript node.js express file-handling