NodeJs : TypeError: require(...) is not a function

NodeJs : TypeError: require(...) is not a function

我正在尝试请求一个文件,然后将其传递给一个 var。我正在按照 this 教程创建身份验证系统。在编写 server.js 文件并尝试编译后,我遇到了一个 BSON 错误,因此我在 mongoose 中更改了需要发布版本的行。

这是我的代码和错误:

server.js

require('./app/routes')(app, passport);

错误

require('./app/routes')(app, passport);
                   ^

TypeError: require(...) is not a function
           at Object.<anonymous> (d:\Node JS learning\WorkWarV2\server.js:38:24)
           at Module._compile (module.js:434:26)
           at Object.Module._extensions..js (module.js:452:10)
           at Module.load (module.js:355:32)
           at Function.Module._load (module.js:310:12)
           at Function.Module.runMain (module.js:475:10)
           at startup (node.js:117:18)
           at node.js:951:3

Process finished with exit code 1

我读到这通常意味着 requireJS 没有正确加载,但我不知道为什么或如何修复它。

因评论而编辑:

如问,hereconsole.log(require);

的结果

我认为这意味着您的 ./app/routes 模块中的 module.exports 未分配为函数,因此 require('./app/routes') 未解析为函数,因此您无法调用它作为这样的函数 require('./app/routes')(app, passport)

如果您希望我们对此发表进一步评论,请告诉我们 ./app/routes

它应该看起来像这样;

module.exports = function(app, passport) {
    // code here
}

您正在导出一个可以像 require('./app/routes')(app, passport) 那样调用的函数。


可能发生类似错误的另一个原因是,如果您有一个循环模块依赖关系,其中模块 A 试图 require(B) 而模块 B 试图 require(A)。当这种情况发生时,它会被 require() 子系统检测到,并且其中一个会作为 null 返回,因此尝试将其作为函数调用是行不通的。这种情况下的解决方法是消除循环依赖,通常是通过将公共代码分解为第三个模块,这两个模块都可以单独加载,尽管修复循环依赖的细节对于每种情况都是唯一的。

对我来说,这是一个循环依赖的问题。

IOW,模块A需要模块B,模块B需要模块A。

所以在模块 B 中,require('./A') 是一个空对象而不是函数。

How to deal with cyclic dependencies in Node.js

记得导出你的routes.js

routes.js中,在这个功能模块中写下你的路由和所有代码:

exports = function(app, passport) {

/* write here your code */ 

}

对我来说,当我执行立即调用函数时,我需要在 require() 的末尾添加 ;

错误:

const fs = require('fs')

(() => {
  console.log('wow')
})()

好:

const fs = require('fs');

(() => {
  console.log('wow')
})()

对我来说,在分支之间切换时我遇到了类似的错误 - 一个使用更新的 ("typescriptish") 版本的 @google-cloud/datastore 包,其中 returns 对象与 Datastore 构造函数作为属性之一导出对象,我切换到另一个分支执行任务,那里使用了一个旧的数据存储版本,它将数据存储构造函数 "directly" 导出为 module.exports 值。我收到错误是因为 node_modules 仍然有我切换的分支使用的较新模块。

我也遇到过这样的事情。 在您的路由文件中,将函数导出为这样的对象:

 module.exports = {
     hbd: handlebar
 }

并且在您的应用程序文件中,您可以通过 .hbd 访问该功能 而且没有问题....!

在我的例子中,当我将 S 放入 module.exportS、

时,我修复了

之前:

module.export = () => {}

之后:

module.exports = () => {}

我不知道怎么做,但在我更改后可能会修复

require('./routes')(app)

require('./routes')