Socket.io不起作用

时间:2017-04-29 12:45:57

标签: node.js socket.io

我已通过" npm install --save socket.io"安装了socket.io。并尝试以下列方式使用;

var express = require('express');
var app = express()
var router = express.Router();
var guestbookData = require('./guestbook.json');
var bodyParser = require('body-parser');
var fs = require('fs');
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(bodyParser());

// set the view engine to ejs
app.set('view engine', 'ejs');

// index page 
app.get('/', function(req, res) {
    res.render('pages/index', {
        new_title: "Guestbook App",
        new_paragraph: "Official Guestbook app."
    });
});

// socket checks user a user connected or disconnected
io.on('connection', function(socket){
  console.log('a user connected');
});

// JSON 
app.get('/guestbook', function(req, res) {
    var data = require('./guestbook.json');

    var table =
     '<table border="1"> ';
    for (var i=0; i < data.length; i++){
        table +=
        '<tr>' +
        '<td>' + data[i].id + '</td>' +
        '<td>' + data[i].username + '</td>' +
        '<td>' + data[i].country + '</td>' +
        '<td>' + data[i].date + '</td>' +
        '<td>' + data[i].message + '</td>' +
        '</tr>';
    }
    res.send(table);
});

// create the form
app.get('/newmessage', function(req, res){
  var html = '<form action="/newmessage" method="post">' +
               'Username:' +
               '<input type="text" name="username" placeholder="..." />' +
               'Country:' +
               '<input type="text" name="country" placeholder="..." />' +
               'Message:' +
               '<input type="text" name="message" placeholder="..." />' +
               '<br>' +
               '<button type="submit">Submit</button>' +
            '</form>';

  res.send(html);
});

// get the form data
app.post('/newmessage', function(req, res){
  var data = require('./guestbook.json');
  nextid = (data.length + 1);
  console.log(nextid)
  data.push({
  "id": nextid,
  "username" : req.body.username,
  "country" : req.body.country,
  "date" : new Date(),
  "message" : req.body.message
  });


// Convert JSON to string
var jsonString = JSON.stringify(data);

//Write new data to file
fs.writeFile('guestbook.json', jsonString, (err) => {
    if(err) throw err;
    console.log('Data saved!');
});

res.send("The new data saved to the file.");
});

// declaring static css
app.use(express.static(__dirname + '/public/'));


app.listen(8080);
console.log('8080 port');
;

然后我将以下内容添加到我的html文件的标题部分;

    <script src="/socket.io/socket.io.js"></script>
      <script>
        var socket = io();
      </script>

但是,当我启动应用程序并重新加载网页时,socket.io不会打印“用户连接”和“#39;到控制台。我的控制台没有显示任何错误迹象,网站正常工作,所以我真的不知道出了什么问题。

如果你能帮助我,我将不胜感激。

0 个答案:

没有答案