找不到套接字IO(404)



我在让socket-io在他们教程中的示例之外工作时遇到了一些问题。

问题是当我想从本地apache服务器上的网站调用chatDiv.html时。

我有一个名为index.js 的节点js服务器

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.get('/', function(req, res){
  res.sendFile(__dirname + '/chatDiv.html');
});
io.on('connection', function(socket){
console.log('a user connected');
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
    console.log(msg);
  });
});
http.listen(3000, function(){
  console.log('listening on *:3000');

服务器加载的客户端文件是chatDiv.html

<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<div class="chat body">
<ul style="width:100%;height:100px;" id="messages"></ul>
<input style="width:100px;height:20px"id="m" autocomplete="off">  </input><button id="sendM"   >Send</button>
    
</div>

最后,我想从我的apache服务器与socket io进行交互。我通过将chatDiv.html的内容加载到类似的容器中来实现这一点

<script src="http://localhost:3000/socket.io/socket.io.js"></script>
$( document ).ready(function() {
  $("#chatContainer").load("http://localhost:3000/", function() {
    console.log('loaded chatdiv');
    var socket = io();
    $( "#chatContainer" ).on( "click", "#sendM", function() {
      console.log('clicked');
    }); 
  }); 
});

现在chatDiv的内容正在加载到我的网站上,我可以看到一个套接字io文件正在加载。但它在调用时出错var socket=io();

GET http://localhost/socket.io/?EIO=3&transport=polling&t=L8zL8x0 404 (Not Found)

您能具体说明您的错误吗?您可能想在io()周围包装一个try-catch块,看看它是否给您任何提示。我怀疑这与您的端口访问权限或防火墙设置有关。

示例:

$( document ).ready(function() {
    $("#chatContainer").load("http://localhost:3000/", function() {
        console.log('loaded chatdiv');
        try{
           var socket = io();
        }
        catch(e){
           //log the error here
           console.log(e);
        }
        $( "#chatContainer" ).on( "click", "#sendM", function() {
            console.log('clicked');
        }); 
    }); 
});

相关内容

  • 没有找到相关文章

最新更新