io.connect();未初始化,node.js

时间:2014-02-06 08:56:08

标签: node.js express socket.io

我正在http://code.tutsplus.com/tutorials/node-js-better-performance-with-socket-io-and-dot--net-35076本指南的帮助下制作我的项目......

我的index.js是

var express = require('express');
//var dot = require('dot').template;
//var fs = require('fs');
var sio = require('socket.io');

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

server.listen(8080);

var posts = [
    { avatar: 'av1.gif', author: 'Jane Doe', text: 'Lorem ipsum ' },
    { avatar: 'av2.png', author: 'John Doe', text: 'Nam interdum'},
    { avatar: 'av3.jpg', author: 'Jeffrey Doe', text: 'Ineger at.' }
];

app.use(express.static('./static'));
app.use(express.bodyParser());

//var postTemplate = dot(fs.readFileSync('./post.dot'));

app.get('/getpost', function (req, res) {
    res.end(postTemplate(posts[Math.floor(Math.random() * 3)]));
});

我的main.js文件是

var postTemplate = function (it) { var out='<div class="post"><div class="some-fblike-nested-div-one"><div class="some-another-nested-div"><div class="nested-div-for-avatar another-long-class"><img src="'+( it.avatar )+'"></div><div class="one-more-div-for-text-here with-some-long classes-to-format-it"><p><span class="author-also-wants-to have-some-fancy-span"><b>'+( it.author )+'</b>:<br></span>'+( it.text )+'</p></div></div></div></div>';return out; }

var socket = io.connect();


$(function () {
    $('button').on('click', function () {
        socket.emit('getpost');
    });
});


socket.on('getpost', function (data) {
    $('button').after(postTemplate(data));
});

问题是main.js中的函数

var socket = io.connect();

永远不会工作,,,,并且浏览器控制台上的错误是 Uncaught ReferenceError: io is not defined ......任何帮助都是令人难以置信的......请

1 个答案:

答案 0 :(得分:1)

您是否在页面/响应中包含了socket.io脚本。

<script src="/socket.io/socket.io.js"></script>

浏览器需要使用socket.io-client API连接到socket.io服务器。