在express中找不到socket.io.js

时间:2018-07-31 12:58:40

标签: node.js express socket.io chat

我的socket.io文件夹结构如下:

  
      
  • node_modules / socket.io /
  •   

我的socket.io.js的文件夹结构如下:

  

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

var express = require('express');
var http= require('http').Server(express);
var io= require('socket.io') (http);
var app = express();

 io.on('connection', function(socket){
    socket.on('chat', function(msg){
        io.emit('chat',msg);
    });
 });

io.on('disconnect', function() {
    console.log('user is disconnected');
});

视图如下:

<script src="/node_modules/socket.io-client/dist/socket.io.js"></script>
  <script src="/js/jquery-2.1.4.min.js"></script>

<script>
$(function(){
    var socket= io();
    $('form').submit(function(e){
        e.preventDefault();
        socket.emit('chat', $('#input').val());
        $('#input').val('');
    return false;
    });

    socket.on('chat', function(msg){
        $('#sent').append(msg);
    });        
});     
</script>

错误是:

Failed to load resource: the server responded with a status of 404 (Not Found)

Uncaught ReferenceError: io is not defined

2 个答案:

答案 0 :(得分:0)

无需创建服务器即可创建套接字实例,您可以将应用传递到socket.js,也可以将套接字导出到其他模块并相应地使用...。应该是这样

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

答案 1 :(得分:0)

首先,node.js服务器默认不提供任何文件。对于要由服务器提供服务的文件,必须有一个路由处理程序,该处理程序具有发送该特定文件的代码。因此,这说明了为什么这不起作用:

 <script src="/node_modules/socket.io-client/dist/socket.io.js"></script>

因为服务器中没有路径"/node_modules/socket.io-client/dist/socket.io.js"的路由处理程序。

但是,socket.io为您解决了这个问题。 socket.io服务器会自动为以下应用安装路由:

/socket.io/socket.io.js

它会到达该node_modules / socket.io / client目录,并在看到上述请求时发送socket.io.js文件。

因此,将您的脚本标签更改为:

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

然后,socket.io服务器将自动从dist目录发送socket.io.js文件。


服务器初始化似乎也不正确,因为您没有将express传递给http服务器,而是传递了app。更改此:

var express = require('express');
var http= require('http').Server(express);
var io= require('socket.io') (http);
var app = express();

io.on('connection', function(socket){
    socket.on('chat', function(msg){
        io.emit('chat',msg);
    });
 });

io.on('disconnect', function() {
    console.log('user is disconnected');
});

对此:

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

io.on('connection', function(socket){
    socket.on('chat', function(msg){
        io.emit('chat',msg);
    });
 });

io.on('disconnect', function() {
    console.log('user is disconnected');
});

或更简单的版本:

var express = require('express');
var app = express();
var server = app.listen(80);
var io = require('socket.io')(server);

io.on('connection', function(socket){
    socket.on('chat', function(msg){
        io.emit('chat',msg);
    });
 });

io.on('disconnect', function() {
    console.log('user is disconnected');
});