【问题标题】:Express.io, socket.io.js not foundExpress.io、socket.io.js 未找到
【发布时间】:2013-03-03 16:17:46
【问题描述】:

我遇到了 Express.io 的问题,我尝试创建一个简单的 tchat。但是我无法包含 socket.io.js,我遇到了一个错误...

我刚刚在我的新 Express 项目中安装了 Express.io。

我的错误:

  1. GET http://***/socket.io/socket.io.js 404(未找到)
  2. localhost:1 Uncaught ReferenceError: io is not defined

Index.jade

doctype 5
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content
    script(src="http://localhost:3000/socket.io/socket.io.js")
    script(src="/javascripts/user.js")

app.js

/**
 * Module dependencies.
 */

var express = require('express.io')
    , index = require('./routes/index.js')
    , http = require('http')
    , path = require('path');

var app = express();

app.http().io();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', index.index);

app.io.route('ready', function(req) {
    req.io.emit('talk', {
        message: 'io event from an io route on the server'
    });
});

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

index.js(路由)

exports.index = function(req, res){
    res.render('index', {
        title: 'TCHAT'
    });
};

user.js

io = io.connect();

// Emit ready event.
io.emit('ready');

// Listen for the talk event.
io.on('talk', function(data) {
    alert(data.message);
});

新错误

加载资源失败:服务器响应状态为 404 (Not Found) http://*:3000/socket.io.js Uncaught ReferenceError: io is not defined

【问题讨论】:

  • 你的节点版本是多少?在尝试复制时,我在节点 0.6.18 上的 socket.io-client 期间遇到了一个 npm 安装错误,如果你在 0.6.x 上,这可以解释事情
  • 尝试从根目录中包含socket.io.js,就像您对user.js 所做的那样:script(src="/socket.io/socket.io.js")
  • 几乎相同的东西...见上文。 (新错误)
  • 我不明白我应该做什么?!删除 socket.io ?

标签: node.js express socket.io


【解决方案1】:

老兄,你在http 服务器而不是express.io 服务器上收听。改变这个

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

到这里:

app.listen(app.get('port'), function(){
   console.log("Express server listening on port " + app.get('port'));
});

那么你就可以访问socket.io.js

【讨论】:

  • @JonathanLonowski 是的,Express 3.x 确实如此,但在 express.io 中,您同时监听 http 和 socket.io,这就是他无法访问 socket.io 服务器/函数的原因跨度>
  • 啊。是的。错过了它重新定义app.listen() 以使用app.server.listen(...)
猜你喜欢
  • 2012-04-28
  • 2016-10-06
  • 2013-11-06
  • 2013-10-25
  • 2014-10-20
  • 2012-05-20
  • 2012-08-09
  • 1970-01-01
  • 2019-01-26
相关资源
最近更新 更多