【问题标题】:Node.js https.createServer throws TypeError: listener must be a functionNode.js https.createServer 抛出 TypeError: listener must be a function
【发布时间】:2014-07-26 21:49:46
【问题描述】:

我已经阅读了所有关于这个的帖子,我知道这一定很愚蠢,但我不明白为什么下面的代码会抛出“TypeError: listener must be a function

假设选项

var server = https.createServer(options, function(request,response){
if (request.url==='/') request.url='/home/altronic/Opti-Cal/web/arimonitor.htm';
console.log("Request: " + request.url);
fs.readFile("public"+request.url,function(error,data){
    if (error) {
        response.writeHead(404, {"Content-type":"text/plain"});
        response.end ("Sorry the page you requested was not found.");
    } else {
        response.writeHead(200,{"Content-type":mime.lookup('public'+request.url)});
        response.end (data);

            }
})
}).listen(port);

控制台输出:

events.js:130
throw TypeError('listener must be a function');
      ^
TypeError: listener must be a function
at TypeError (<anonymous>)
at Server.EventEmitter.addListener (events.js:130:11)
at new Server (http.js:1816:10)
at Object.exports.createServer (http.js:1846:10)
at Object.<anonymous> (/home/altronic/Opti-Cal/src/Opti-Cal_HTTPS_Server.js:42:20)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)

谁能帮我解决这个问题?

【问题讨论】:

    标签: javascript node.js https


    【解决方案1】:

    你在哪里分配https?看起来您可能需要http,而不是httpshttp.createServer 不接受 https.createServer 之类的选项。

    【讨论】:

    • +1 我认为这正是正在发生的事情。它会产生完全相同的错误。
    • 堆栈跟踪在http.js 中显示了一个框架,所以这似乎很有可能。
    • 谢谢。这正是问题所在!
    【解决方案2】:

    我有同样的错误信息:

    throw TypeError('listener must be a function');

    我有两个单独的文件 server.js 和 handler.js。 我的问题是当我需要(require(./handler.js))我在 server.js 中的处理程序文件时,我没有从 handler.js 文件中导出它。您必须拥有:module.exports =handler;在处理程序文件的底部

    【讨论】:

      【解决方案3】:

      您在使用节点版本

      查看文档和历史记录。我很困惑,文档说我可以在 http.createServer 上使用选项对象并得到这个错误,直到我意识到我有一段时间没有更新节点。

      https://nodejs.org/api/http.html#http_http_createserver_options_requestlistener

      【讨论】:

        【解决方案4】:

        这主要来自版本不匹配。最新版本的 nodejs 的 http.createServer() 确实像 https 一样在参数中采用选项。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-18
          • 2017-04-08
          • 1970-01-01
          • 2019-06-18
          • 2021-11-22
          • 2016-10-10
          • 2016-06-17
          • 1970-01-01
          相关资源
          最近更新 更多