node.js不打印到控制台

时间:2017-06-13 01:25:00

标签: javascript node.js socket.io

我正在尝试在api中使用套接字。但是我无法在控制台中看到日志。

我看到的唯一输出是:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
We are live on8000

这是我的server.js文件:

// server.js
const express        = require('express');
const MongoClient    = require('mongodb').MongoClient;
const bodyParser     = require('body-parser');
const app            = express();
const port           = 8000;

var server = require('http').createServer(app);
var io = require('socket.io')(server);

const db = require('./config/db');

app.use(express.static(__dirname + '/../app'));
app.use(bodyParser.urlencoded({ extended: true }));


MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err);

    //check below line changed
     require('./app/routes')(app, database);
    app.listen(port,() => {
        console.log("We are live on"+port);
    });

    app.get('/', function(req, res){
      res.sendFile(__dirname + '/index.html');
    });


    io.on('connection',function(socket){
      console.log('client connected');

      socket.on('disconnect', function () {
        console.log('disconnect');
      });

    });

})

并且index.html是:

<!DOCTYPE html>
<html>
  <head><title>Hello world</title></head>
  <script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>
  <body>Hello world</body>
</html>

我在网络浏览器上看到了Hello world,但我在控制台日志中看不到“客户端连接”。

2 个答案:

答案 0 :(得分:1)

更新:在您的浏览器客户端中,您可以在console.log http://localhost:8000/socket.io/socket.io.js 404(index):6 Uncaught ReferenceError: io is not defined

中看到错误

您已将socket handler附加到http服务器var io = require('socket.io')(server);,但在您的代码中,您可以express server启动网络服务器

app.listen(port,() => {
        console.log("We are live on"+port);
    });

将其更改为

server.listen(port,() => {
        console.log("We are live on"+port);
    });

答案 1 :(得分:0)

我创建了一个新的.js文件,并且正在侦听端口3000而不是8000用于socket.io

appsocket.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

//Whenever someone connects this gets executed
io.on('connection', function(socket){
  console.log('A user connected');

  //Whenever someone disconnects this piece of code executed
  socket.on('disconnect', function () {
    console.log('A user disconnected');
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

现在,当我调用localhost:3000而不是localhost时,我能够在控制台上看到日志:8000