节点服务器,Socket.io“io未定义”?
我遵循了之前一直对我有用的完全相同的步骤,通过express创建应用程序,将模块依赖项放置在node_modules文件夹中。似乎未找到 socket.io 客户端 JavaScript 文件。
(我查看了其他人的修复,即将 JavaScript 文件包含在脚本选项卡中。我之前的 Node + socket.io 项目不需要这样做)。
客户端上的 JavaScript:
var socket = io.connect('http://localhost');
服务器上的 JavaScript:
var io = require('socket.io').listen(app);
node_modules 文件夹:
socket.io, which has an internal node_modules folder containing socket.io-client
错误消息:
Uncaught ReferenceError: io is not defined
(anonymous function)
当我包含套接字时手动.io客户端: http://cdn.socket.io/stable/socket.io.js
我收到不同的错误这是:
Uncaught TypeError: Object #<Object> has no method 'connect'
(anonymous function)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在客户端上,您是否执行以下操作:
在设置
socket
变量之前?On the client, did you do:
before you set the
socket
variable?Node.js 新手来了!
我很确定这个问题已经得到解答。然而我不断发现套接字的 src 存在问题。显然这个:
在客户端对我不起作用。
我已经用这个替换了上面的行,它看起来工作正常。
(编辑:虽然这是显而易见的,但根据您阅读此答案的时间,此链接可能不起作用。请从以下位置选择最新链接:https://cdnjs.com/libraries/socket.io)
这是一个有效的客户端代码:
在服务器端 (仅处理 1 个套接字)
Node.js newbie here!
I am pretty sure this has been answered. Yet I kept finding problems with the src for the socket. Apparently this :
<script src="/socket.io/socket.io.js">
was not working for me on the client side.I've replaced the above line with this and it seems to work fine.
(Edit: although this is obvious, this link may not work depending on when you are reading this answer. Please pick the latest link from: https://cdnjs.com/libraries/socket.io)
Here is a working client side code:
On the server side (handles only 1 socket)
我设法解决了这个问题,并浪费了大约一个小时,结果证明这是一个非常基本的错误。
当函数未定义时?如“Uncaught ReferenceError:io未定义”。
这是否意味着该函数在“创建”之前就已被“使用”?
在我的 HTML 文件中,“调用”javaScript 文件,
它看起来像这样:
我将其更改为这样
所以现在项目“io”,无论是对象还是函数......实际上是在使用之前创建的:D
玩得开心!
I managed to blunder through this, and squandered about an hour, on something that turned out to be a very basic error.
When an function is not defined? Such as " Uncaught ReferenceError: io is not defined ".
Does that not mean that the function is getting "used" before it is "created"?
In the part of my HTML file, that "calls" the javaScript files,
it look like this :
and i changed it to this
So now the item "io", whether it is an object or function... Is actually getting created before it is getting used :D
Have FUN!
在客户端:
On the client:
我通过 Node.js 服务器运行索引页面解决了这个问题。
正如网址中提到的
未捕获的引用错误:io未定义
所以当我执行
https://localhost:3000
时(3000是nodejs所在的端口开始)错误已解决。I solved this by running the index page by the Node.js server.
as mentioned in the url
Uncaught ReferenceError: io is not defined
So when I executed
https://localhost:3000
(3000 the port where the nodejs has been started) the error got resolved.确保使用最新的 CDN 版本。
Make sure use the latest CDN version.