NodeJS - TypeError: app.listen is not a function

5
我知道这个问题已经有答案了,但是它们并没有解决我的问题。 错误是“TypeError:app.listen不是一个函数”; 下面是完整的代码,谢谢。(PS,我没有在同一个端口上运行任何东西)
var io = require('socket.io')(app);
var fs = require('fs');
var serialPort = require("serialport");

var app = require('http');

app.createServer(function (req, res) {
    fs.readFile(__dirname + '/index.html',
        function (err, data) {
            res.writeHead(200);
            res.end(data);
        });
}).listen(1337, '127.0.0.1');


var port = new serialPort(process.platform == 'win32' ? 'COM3' : '/dev/ttyUSB0', {
    baudRate: 9600
});

port.on( 'open', function() {
    console.log('stream read...');
});

port.on( 'end', function() {
    console.log('stream end...');
});

port.on( 'close', function() {
    console.log('stream close...');
});

port.on( 'error', function(msg) {
    console.log(msg);
});

port.on( 'data', function(data) {
    console.log(data);

    var buffer = data.toString('ascii').match(/\w*/)[0];
    if(buffer !== '') bufferId += buffer;

    clearTimeout(timeout);
    timeout = setTimeout(function(){
        if(bufferId !== ''){
            id = bufferId;
            bufferId = '';
            socket.emit('data', {id:id});
        }
    }, 50);
});

io.on('connection', function (socket) {
    socket.emit('connected');
});

app.listen(80);

嗨,Adeneo,我对NodeJS还比较新,请问你能解释一下你的意思吗? - Peter Bennett
我有点困惑,你在第一行使用了 app,将其传递给 socket.io,但是直到第五行才定义它? - adeneo
文档中有一些示例,你试过这些吗 -> https://nodejs.org/api/http.html#http_event_connect - adeneo
3个回答

9

这可能不是对SO问题的回答,但在类似于test的情况下,相同的错误“TypeError:app.listen不是函数”可能可以通过导出模块app来解决。

$ ./node_modules/.bin/mocha test

可以输出
TypeError: app.listen is not a function

解决方案:

尝试在 server.js 文件底部添加以下内容:

module.exports = app;

谢谢,我的错误是module.exports = app;。 - AllisLove

6
错误来自于这一行:
app.listen(80);

由于app是你的http模块var app = require('http');,你试图监听node http模块(但你不能这样做)。你需要使用该http模块创建一个服务器,然后监听它。

这就是你用这些行所做的:

app.createServer(function (req, res) {
    fs.readFile(__dirname + '/index.html',
        function (err, data) {
            res.writeHead(200);
            res.end(data);
        });
}).listen(1337, '127.0.0.1');

基本上,http.createServer() 返回一个 http.server 实例。该实例具有一个 listen 方法,该方法使服务器在指定端口上接受连接。
因此,以下代码可以正常工作:
var app = require('http');
app.createServer().listen(8080);

这是不允许的:

var app = require('http');
app.listen(8080);

HTTP模块文档: https://nodejs.org/api/http.html#http_http_createserver_requestlistener


1
清除您那里的所有代码,然后尝试。
const http = require('http');
const handleRequest = (request, response) => {
  console.log('Received request for URL: ' + request.url);
  response.writeHead(200);
  response.end('Hello World!');
};

const www = http.createServer(handleRequest);
www.listen(8080);

然后访问localhost:8080…以查看页面的响应。

但是,如果您想处理页面路由,我建议先使用expressjs 点击此处获取指南。一旦这个工作正常,您就可以再添加socket.io代码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接