节点.js / socket.io / socket.io.js未找到。

53

我一直收到这个错误消息:/socket.io/socket.io.js 404 (Not Found) Uncaught ReferenceError: io is not defined

我的代码是:

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

server.listen(3000);

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

问题是什么?

欢迎任何帮助!


可能是Socket.io未被Node.js服务器提供的重复问题。 - Ron van der Heijden
@robertklep:啊不,我有一个index.html页面...从app.js中获取信息:socket.io已启动。 - hausinho
@Bondye 不,这不是问题所在。 - robertklep
2
@hausinho 如果你的HTML文件是由不同的服务器提供的,那么你需要包含socket.io文件的完整URL:<script src="http://localhost:3000/socket.io/socket.io.js"></script>(或者其他主机名)。 - robertklep
@hausinho 应该是 http://localhost:3000/socket.io/socket.io.js,试试看。 - robertklep
显示剩余11条评论
11个回答

85

socket.io.js 复制到公共文件夹(例如 resources/js/socket.io.js)并不是正确的做法。

如果 Socket.io 服务器正确监听了你的 HTTP 服务器,它会自动通过 http://localhost:<端口号>/socket.io/socket.io.js 提供客户端文件,你不需要手动查找或复制到公开可访问的文件夹中,如 resources/js/socket.io.js 并进行手动服务。

代码示例
Express 3.x - Express 3 要求你先实例化一个 http.Server,然后才能附加上 socket.io

var express = require('express')
  , http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

//... 

server.listen(8000);

编程愉快 :)


3
这应该是此socket.io问题的经过验证的答案。谢谢! - Nizar B.
46
我曾经遇到过类似的问题,与我正在重构的旧代码有关,该代码使用了app.listen(3000)。然而这并没有起作用。当我将其改为server.listen(3000)时,它就开始正常工作了。 - edufinn
我建议更新调用“var socket = io('http:// localhost);”的index.html,以使用正确的端口。 - emeraldjava
啊!你把服务器注入到了监听方法中。谢谢! - trixtur
@edufinn 哇,你真的太棒了。问题就是那个。谢谢你。 - testing_22
客户端代码会是什么样子呢? - jsirr13

13
如何在客户端找到 socket.io.js?
安装 socket.io。
npm install socket.io

寻找socket.io客户端

find ./ | grep client | grep socket.io.js

结果:

./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js

将socket.io.js复制到您的资源文件夹中:

cp ./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js /home/proyects/example/resources/js/
在你的HTML中:
<script type="text/javascript" src="resources/js/socket.io.js"></script>

好的,我将socket.io.js文件复制到一个名为js的文件夹中,现在它是这样的<script src="js/socket.io.js"></script> - 但现在我收到了错误http://localhost:3000/socket.io/1/?t=1382087281918 !?!?!? - hausinho
这不是错误,而是连接请求,您必须在服务器/客户端中创建事件以进行通信。 - ZiTAL
+1,在搜索了几个小时后,我终于找到了这个源代码,其中有一个可以复制到lib中的socket.io.js。 - A.Kalkhoff
当仅使用客户端而没有服务器时,这是一个有用的解决方案。 - traeper

9

看起来这个问题可能从未得到答复(尽管对于提问者来说可能为时已晚),但我会回答它以供未来遇到此类问题的人使用解决方案。

你需要执行 npm install socket.io --save 而不是 npm install socket.io,这样socket.io模块就会安装在你的web开发文件夹中(在基础位置/索引.html或index.php所在位置运行此命令)。这将使socket.io安装在命令运行的区域,而不是全局,并且还会自动更正/更新您的package.json文件,以便node.js知道它的存在。

然后将源路径从'/socket.io/socket.io.js'改为'http://' + location.hostname + ':3000/socket.io/socket.io.js'


3

您可能会想知道/socket.io/socket.io.js文件是从何处来的,因为我们既没有添加它,也没有在文件系统中存在。这是io.listen在服务器上完成的魔法的一部分。它在服务器上创建一个处理程序,用于提供socket.io.js脚本文件。

来自书籍《Socket.IO实时Web应用开发》,第56页


这还不足以回答这个问题。 - alfredo

1
请检查您代码中提到的目录路径。默认情况下是 res.sendFile(__dirname + '/index.html');。请确保您的 index.html 文件在正确的目录中。

1

你只需按照 https://socket.io/get-started/chat/ 的步骤操作,一切都会正常工作。

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
  console.log('listening on *:3000');
});

1
如果您想手动下载“socket.io/socket.io.js”文件并将其附加到html(而不是从服务器运行时获取),则可以使用https://cdnjs.com/libraries/socket.io,类似于这样。
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js" integrity="sha512-eVL5Lb9al9FzgR63gDs1MxcDS2wFu3loYAgjIH0+Hg38tCS8Ag62dwKyH+wzDb+QauDpEZjXbMn11blw8cbTJQ==" crossorigin="anonymous"></script>

1

调试步骤

  1. npm install socket.io --save in static files (index.html) for example, you may have installed it globally and when you look at the debugger, the file path is empty.

  2. Change your script file and instantiate the socket explicitly adding your localhost that you have set up in your server file

     <script src="http://localhost:5000/socket.io/socket.io.js"></script>
         <script>
           const socket = io.connect("localhost:5000");
            $(() =>
    

    Double check that the data is flowing by opening a new browser tab and pasting http://localhost:5000/socket.io/socket.io.js you should see the socket.io.js data

  3. Double check that your server has been set-up correctly and if you get a CORs error npm install cors then add it to the server.js (or index.js whatever you have chosen to name your server file)

     const cors = require("cors");
     const http = require("http").Server(app);
     const io = require("socket.io")(http);
    

    Then use the Express middleware app.use() method to instantiate cors. Place the middleware this above your connection to your static root file

     app.use(cors());
     app.use(express.static(__dirname));
    
  4. As a final check make sure your server is connected with the http.listen() method where you are assigning your port, the first arg is your port number, for example I have used 5000 here.

     const server = http.listen(5000, () => {
       console.log("your-app listening on port", server.address().port);
     });
    
  5. As your io.on() method is working, and your sockets data is connected client-side, add your io.emit() method with the callback logic you need and in the front-end JavaScript files use the socket.on() method again with the call back logic you require. Check that the data is flowing.

我还编辑了上面的一条评论,因为它对我最有用 - 但是我需要采取一些额外的步骤来使客户端-服务器连接正常工作。


1
如果您正在按照socket.io教程https://socket.io/get-started/chat/进行操作,应该按以下方式添加此行。
app.use(express.static(path.join(__dirname, '/')))

这是因为在教程中,Express 只会捕获网址 / 并发送 index.html 文件。
app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html')
})

然而,在index.html中,您有一个脚本标签(<script src="/socket.io/socket.io.js"></script>)请求了socket.io-client的资源,但在index.js中没有路由它(可以在控制台网络中找到url为http://localhost:3000/socket.io/socket.io.js)。

0
如果在开发过程中出现这种情况,可能原因之一是您正在运行客户端文件(index.html)。但您应该做的是运行服务器(例如在localhost:3000上),让服务器处理静态文件(index.html)。这样,socket.io包将自动使
<script src="/socket.io/socket.io.js"></script> 在客户端上可用。
说明(文件名:index.js):
const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const port = 3001 || process.env.PORT;
const app = express();
const server = http.createServer(app);
const io = socketio(server);

//MiddleWares
app.use(express.json());
app.use(
  express.urlencoded({
    extended: false,
  })
);
app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
  res.sendFile('index.html');
});

io.on('connect', (socket) => {
console.log('New user joined');
}
server.listen(port, () => {
  console.log(`App has been started at port ${port}`);
});

在执行以下命令后运行您的服务器文件: node index.js 然后打开localhost:${port},将端口替换为index.js文件中给定的端口并运行它。

这解决了我的问题。希望它也能解决你的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接