简体   繁体   中英

Module.exports in JavaScript

What is different between module.exports = testMethod; and module.exports = { testMethod }; Because when I am using 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 };

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. 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.

Strange for me, on Cloud9 on Aws i have no problems.

Both are worked to export your module to outside function. But when you are using any callback function with

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.

you can do something like this to work,

module.exports = somectrl()

or

module.exports = new somectrl()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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