繁体   English   中英

nodejs,socket.io和expressjs无法连接

[英]nodejs, socket.io and expressjs not connecting

我有一个类似的文件夹结构:

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://协议,这一事实使我认为您正在直接打开html文件。 在该src字符串之后,您还会缺少引号。

确保您正在加载localhost:3000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM