首页 文章

无法使用node.js加载socket.io:未定义io

提问于
浏览
0

我使用express-generator生成了一个快速应用程序,当包含socket.io时,我注意到socket.io客户端没有被浏览器加载 . 我已经在互联网上搜索了2天没有成功的解决方案 .

我遵循了express 3/4的socket.io指令,实际上服务器/socket.io/socket.io.js上的服务器公开的socket.io客户端正在服务(没有404错误) . The problem is that when javascript code that tries to use socket io client fails because "io is not defined"

Any ideas about why the browser is not loading the client although it states that HTTP GET to http://localhost:8080/socket.io/socket.io.js returns HTTP 200?

顺便说一句,该应用程序也使用Angular.js .

的index.html

<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script type="text/javascript">
 // Uncaught ReferenceError: io is not defined
 var socket = io.connect('http://localhost:8080');
</script>

app.js(没有错误日志和socket.io服务器调试消息说“socket.io:server服务客户端源3s”)

// setup server
app.set('port', process.env.PORT || 8080);

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

console.log(app.get('port'));

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

});


io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Update:

通过使用socket.io CDN,结果是一样的 . 这是行不通的

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

1 回答

  • 0

    我在回答我自己的问题 . 我终于找到了解决这个问题的方法,但我仍然不知道原因是什么 .

    解决方案是在任何其他标签之前移动 <script src="/socket.io/socket.io.js"></script> (有16个脚本声明:angular,bootstrap,jquery,moment等) .

    So if you get "Uncaught ReferenceError: io is not defined" message on the browser move first "" at the beginning of the page inside tags . 它将为您节省大量努力以使其工作 .

相关问题