【发布时间】:2012-07-24 02:11:57
【问题描述】:
我正在尝试开始使用 socket.io 和 node.js。
按照 socket.io 网站上的第一个示例,我在浏览器的控制台中收到以下错误:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3001/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined
这是我的 server.js
var app = require('express').createServer()
, io = require('socket.io').listen(app);
app.listen(3001);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
这是我的 index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8" />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</body>
</html>
我已经安装了socket.io..
【问题讨论】:
-
看起来它没有在您的服务器上找到 socket.io.js。它在你定义的路径中吗?
-
这个文件在请求路径时应该由node自己托管:/socket.io/socket.io.js。
-
我从未使用过 socket.io.js,但根据您发布的服务器代码,我看不到文件是如何下载的。通常使用 node/express 您可以包含 express.static 以提供该文件或为其定义路由。如果默认情况下提供静态资源,那么我会查看路径。
-
您使用的是哪个版本的 express?
-
这实际上不是 socket.io 的问题,'localhost' 的行为很奇怪,有时不喜欢像真正的 url 一样使用节点。