全局对象在自定义模块中不可用,即使传入并请求也是如此

route1.js 代码:

var express = require('express');
var app = express();
var router = express.Router();
var module1 = require('../modules/module1.js'); // custom module

    var globals = {
        a : 'A',b : 'B',c : 'C'
    };

router.post('/data',function(req,res){
  var data = req.body.form_input;
  // here we update the globals object with the data,mutate it or something
});

module.exports = {
    router : router,globals : globals
};

module1.js 代码:

var route1 = require ('../routes/route1.js');

console.log(route1.globals); // not working!?

为什么即使我通过module.export在route1中将全局导出在module1中也不可用?

编辑:

我需要时发生了循环依赖: var module1 = require('../ modules / module1.js'); 然后在module1中,我需要: var route1 = require('../ routes / route1.js');

,因此它从model1跳到route1,然后又跳到model1再跳到route1,依此类推。通过添加其他模块-globals.js并将其添加到module1并解决了route1问题-感谢@Rashomon。

bianweiby 回答:全局对象在自定义模块中不可用,即使传入并请求也是如此

我认为您在这里有一个循环依赖。循环依赖关系很难管理,并且在多数情况下是体系结构设计不良的标志。 建议您将globals移到一个名为globals.js的文件中。

这里有一个循环依赖问题的最小示例: https://codesandbox.io/s/damp-hill-94gdg?fontsize=14

本文链接:https://www.f2er.com/3131710.html

大家都在问