2016-01-13 59 views
0

嗨,我有一些麻煩,讓套接字io工作超出他們的教程的例子。問題是,當我想從一個網站叫chatDiv.html我的本地Apache服務器沒有找到套接字IO(404)

對我有我的節點JS服務器名爲index.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服務器與插座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) 

回答

0

你可以具體說明你有什麼錯誤嗎?你可能想在你的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'); 
     }); 
    }); 
}); 
+0

錯誤是GET HTTP://localhost/socket.io/ EIO = 3&運輸=輪詢&T = L8zL8x0 404(未找到) 或你需要它來更具體? ? – user2202098

+0

你有沒有嘗試過「sudo」作爲管理員? – YooManFoo