我的文件夹结构如下:
socket
- project
- main.js
-node_modules
- node_modules_folder_here
- text.html
我的 main.js 文件如下所示:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
console.log("inside")
res.send('<h1>Hello again</h1>');
});
io.on('connection', function(socket){
console.log("socket")
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
我正在使用 node main.js
运行服务器,一切正常
我的 test.html 看起来像:
<body>
<h3>Hellooww world</h3>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io();
console.log("check io", socket)
</script>
</body>
</html>
我的 package.json 如下:
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.24.0",
"babel-loader": "^6.4.0",
"express": "^4.15.2",
"node-fetch": "^1.6.3",
"promise": "^7.1.1",
"socket.io": "^1.7.3",
"webpack": "^2.2.1",
"xmlhttprequest": "^1.8.0"
我只是按照 socket.io
教程操作就得到了这个错误
GET file:///socket.io/socket.io.js net::ERR_FILE_NOT_FOUND
test.html:10 Uncaught ReferenceError: io is not defined
如果我在另一个项目中使用这个套接字服务器怎么办?
这里有什么问题吗?我只是遵循 socket.io 教程,我在这里错过了什么?出了什么问题以及为什么??
最佳答案
您的浏览器正在寻找file:///socket.io/socket.io.js
,事实上它假定file://协议(protocol)让我认为您正在打开您的html文件直接地。
src 字符串后面还缺少一个引号。
确保您正在加载localhost:3000
。
关于node.js - nodejs、socket.io 和expressjs 未连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863852/