【问题标题】:TypeError: require(...) is not a function (Node.js) [server.js] [duplicate]TypeError: require(...) is not a function (Node.js) [server.js] [duplicate]
【发布时间】:2017-06-22 18:26:45
【问题描述】:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const port = process.env.PORT || 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true,
}));

app.use('/', require('../routes')(express));

exports.server = app.listen(port, () => {
  console.log('Server active on', port);
});

我是否缺少 npm 包?

错误

TypeError: require(...) is not a function
at Object.<anonymous> (C:\xampp\htdocs\url-shortener\src\server.js:12:34
  at Module._compile (module.js:571:32)
  at Object.Module._extensions..js (module.js:580:10)
  at Module.load (module.js:488:32)
  at tryModuleLoad (module.js:447:12)
  at Function.Module._load (module.js:439:3)
  at Module.runMain (module.js:605:10)
  at run (bootstrap_node.js:418:7)
  at startup (bootstrap_node.js:139:9)
  at bootstrap_node.js:533:3

【问题讨论】:

  • 您的../routes 中有什么内容?
  • 我在module.exports = function (string) { console.log(string); }中将exports 拼错为export

标签: node.js npm


【解决方案1】:

您的 ../routes 源文件未导出函数。

尝试替换这一行:

app.use('/', require('../routes')(express));

与:

console.log( require('../routes') );

我敢打赌它会打印一个对象 ({ ... }) 而不是一个函数。


在您的../routes 文件中,您需要显式导出重要函数:

module.exports = importantFunction;

function importantFunction(string) {
  console.log(string);
}

现在你的脚本可以调用它。

require('../routes')("hi") // should log "hi"

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2016-01-05
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多