NodeJS - TypeError: app.listen不是一个函数



我知道这个问题已经存在了,但是他们的答案并没有解决我的问题。

错误是"TypeError: app.listen is not a function";

我的完整代码如下,提前感谢。(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);

这可能不是SO问题的答案,但在与测试类似的情况下,相同的错误"TypeError: app.listen不是一个函数"可能可以通过导出模块app来解决。

$ ./node_modules/.bin/mocha test

可以输出

TypeError: app.listen is not a function

解决方案:

尝试添加到server.js文件的底部:

module.exports = app;

错误来自这一行:

app.listen(80);

因为app是你的http模块var app = require('http');,你试图听节点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。服务器实例。这个实例有一个listen方法,使服务器接受指定端口上的连接。

所以这个可以工作:

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

this can't:

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

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

清除所有代码,并尝试

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开始,点击这里的指南这样做之后,您就可以添加套接字了。IO代码返回。

最新更新