require和module.exports:TypeError:X不是函数

问题描述 投票:0回答:1

File structure :

server
├── controllers
│   ├── locationsController.js
│   ├── mainController.js
│   └── utilisateursController.js
├── models
│   ├── Locations.js
│   ├── Utilisateurs.js
|   └── ...
├── routes.js
└── server.js

在qazxsw poi我有一个函数qazxsw poi来检查一个字符串,我把它放在那里因为我想从mainControllerisValid访问它。我将其导出如下:

utilisateursController.js

locationsController.js

Problem

我可以从mainController.js访问函数const lc = require('./locationsController'); const uc = require('./utilisateursController'); // ... module.exports = { // Associate all models associateAll: function () { lc.associateLocations(); uc.associateUtilisateurs(); }, isValid: function(...fields) { for (let i = 0; i < fields.length; i++) if (fields[i] === undefined || fields[i] === null || fields[i] === '') return false; return true; } }; ,但是当我尝试从isValid做同样的事情时,我有这个错误:

utilisateursController.js

Code

locationsController.js

从这个文件,我可以完美地访问(node:6461) UnhandledPromiseRejectionWarning: TypeError: mc.isValid is not a function at exports.getAllTasks (.../server/controllers/locationsController.js:30:11) ,没有错误。

utilisateursController.js

isValid

从这个文件,我得到上面提到的错误,我真的不知道为什么...

const mc = require('./mainController');

// ...

exports.login = async function (req, res) {

  let response = {
    // ...
  }
  if (req.query == null) {
    response.infoMsg = 'Query empty...';
    res.send(response);
    return;
  }

  const usernameInput = req.query.username;
  const passwordInput = req.query.password;

  if (!mc.isValid(usernameInput, passwordInput)) {
    response.infoMsg = 'username or password is empty...'
    res.send(response);
    return;
  }

  // ...

}

What I think

我想这可能是因为要求的决议顺序......

What the debugger says

locationsController.js

const mc = require('./mainController'); // ... exports.getAllTasks = async function (req, res) { let response = { // ... } const usernameInput = req.params.username; if (!mc.isValid(usernameInput)) { response.infoMsg = 'No parameters given...'; res.send(response); return; } // ... }

我真的不知道造成这个问题的原因是什么......

javascript node.js export require
1个回答
2
投票

问题是由于你在utilisateursController.jslocationsController.jsmainController之间存在循环关系。 utilisateursControllerlocationsController都需要utilisateursControllerlocationsController需要mainControllermainContoller。因此,Node.js的CommonsJS样式模块解析最终会在至少一个(可能是两个)模块中运行顶级代码,并使用占位符对象来导出其他模块之一。 (显然,在你的情况下,utilisateursController获得了locationsController出口的占位符.locationsController也可以这样做,但不会尝试在顶层使用它。)

如果你避免在顶级使用mainController,只在稍后调用的函数中使用它,那么占位符将在你需要它之​​前填充并且一切都会很好。你引用的代码似乎只在一个函数中使用utilisateursController,但考虑到你得到的错误,显然你的真实代码并不正确。

更多在mc


附注:本机JavaScript模块(通常称为“ECMAScript模块”的“ESM”)不会发生这种情况,因为即使存在循环依赖关系,它们也会在顶级模块代码运行之前得到解决。

© www.soinside.com 2019 - 2024. All rights reserved.