node . js https.createServer抛出TypeError: listener必须是一个函数

Node.js https.createServer throws TypeError: listener must be a function

本文关键字:函数 一个 createServer https js 抛出 TypeError listener node      更新时间:2023-09-26

我读过所有关于这个的帖子,我知道它一定是愚蠢的,但我不明白为什么下面的代码会抛出"TypeError: listener必须是一个函数"

假设选项

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)
有谁能帮我解决这个问题吗?

您将https分配到哪里?看起来你可能需要http,而不是httpshttp.createServer不接受https.createServer等选项

使用节点版本时可能会遇到此错误<9.6

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

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

我有相同的错误信息:

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

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

这主要是由于版本不匹配。最新版本的nodejs的http.createServer()像https一样在参数中接受选项。