【问题标题】:Nodejs : How to use variable from a router in another routerNodejs:如何在另一个路由器中使用来自路由器的变量
【发布时间】:2020-11-15 20:58:59
【问题描述】:

我有一个Express 服务器,我将路由分成两个独立的文件routesA.jsroutesB.js

这里是routesA.js

const aRoutes = (app, fs) => {
    const dataPath = 'example';
};

module.exports = aRoutes;

routesB.js

const aRoutes = require('./routesA');

const bRoutes = (app, fs) => {
    console.log(aRoutes.dataPath);//-> undefined
};

module.exports = bRoutes;

我想读取bRoutes 中的变量dataPath

如何正确地做到这一点?

【问题讨论】:

  • 那你为什么不从aRoutes返回dataPath
  • 它已经在文件末尾以module.exports = aRoutes;导出
  • 所以您是说您不能对aRoutes 进行更改?对于这个问题,了解这一点很重要。可能希望将其包含在问题中。
  • 你指的是什么变化?
  • 您必须指定不能更改routesA.js 文件以便人们帮助您。这从根本上改变了可能的解决方案。

标签: node.js express routes


【解决方案1】:

你调用aRoutes.dataPath 就好像它是一个对象,而它实际上是一个函数。如果你想从aRoutes 返回dataPath 值,那么你需要修复你的代码。

routesA.js

const aRoutes = (app, fs) => {
    const dataPath = 'example';
    return dataPath;
};

module.exports = aRoutes;

routesB.js:

const aRoutes = require('./routesA');

const bRoutes = (app, fs) => {
    console.log(aRoutes()); // You're calling the function and console logging the value
};

module.exports = bRoutes;

【讨论】:

  • 我不能只调用aRoutes() 来获取变量,因为我提到这些文件是服务器的一部分,每个文件内部都有许多路由。 dataPath 是 const 不是函数
  • 您的问题是“如何正确读取 bRoutes 中的 dataPath 的值” 这就是您如何从 bRoutes 读取 dataPath 的值。您可以使用 const dataPath = aRoutes(); 将 dataPath 分配给 bRoutes 中的变量
  • 不行,我试过了!即使它有效,我也不能这样做,你明白我的问题是一个简化的案例,在现实世界中,正如我向你解释的那样,调用 aRoute() 将意味着调用其中的所有路由,这将使我的服务器崩溃.
  • 我认为您的路线设置错误或您的问题不清楚。阅读 Express 文档。他们非常有帮助和清晰。阅读路线和控制器。 gl
  • 这对我没有帮助。我已经做了一千次了,我整天都在尝试解决这个问题,他们的文档实际上并不清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 2021-01-16
相关资源
最近更新 更多