简体   繁体   English

JavaScript 中的模块.exports

[英]Module.exports in JavaScript

What is different between module.exports = testMethod; module.exports = testMethod;之间有什么不同 and module.exports = { testMethod };module.exports = { testMethod }; Because when I am using module.exports = testMethod;因为当我使用module.exports = testMethod; it is throwing error as below.它抛出如下错误。 Error: Route.get() requires a callback function but got a [object Undefined] But I am okay with module.exports = { testMethod };错误:Route.get() 需要回调 function 但得到了 [object Undefined]但我对module.exports = { testMethod };

Whole codes are整个代码是

const testMethod = asyncErrorWrapper(async (req, res, next) => {
  const information = req.body;

  const question = await Question.create({
    title: information.title,
    content: information.content,
    user: req.user.id,
  });

  res.status(200).json({
    success: true,
    data: question,
  });
});

module.exports = { testMethod };

From VSCode, change between the ES5 or ES6 version to Js can take you on a bad way.在 VSCode 中,从 ES5 或 ES6 版本到 Js 之间的更改可能会让您走上一条糟糕的路。 So, be carreful, i have the same problem recently, and after refactoring by use on ES6 module.exports = router to the end of some Js file (Node project using express) it was done.所以,小心点,我最近也遇到了同样的问题,在通过使用 ES6 module.exports = router重构到某个 Js 文件的末尾(使用 express 的 Node 项目)之后,它就完成了。

Strange for me, on Cloud9 on Aws i have no problems.对我来说很奇怪,在 AWS 上的 Cloud9 上我没有问题。

Both are worked to export your module to outside function.两者都可以将您的模块导出到 function 外部。 But when you are using any callback function with但是当您使用任何回调 function 时

module.exports = somectrl

then it will fail but那么它会失败但是

module.exports = { somectrl }

because when you create an object, it actually instanciate it but when you pass a ref function/ const function name then it will behave as a existing function which does not work right.因为当您创建 object 时,它实际上会实例化它,但是当您传递 ref 函数/ const function 名称时,它将表现为现有的 ZC1C425268E68385D1AB5074C17A94F14 无法正常工作。

you can do something like this to work,你可以做这样的事情来工作,

module.exports = somectrl()

or或者

module.exports = new somectrl()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM