2015-07-20 86 views
6

我最近開始學習node.js和socket.io。我跟着一個簡單的教程,socket.io有,而且在我的電腦上運行時,它一切正常。但是,我決定將客戶端部分上傳到服務器進行測試,這就是問題出現的地方。我想在Web主機上運行聊天客戶端,然後在我的計算機或其他主機上運行服務器。基本上,我計劃端口轉發服務器,並讓客戶端運行在網頁上。我打開我的端口來端口,它似乎工作,但我每次都在網頁上發生錯誤。CORS用node.js和socket.io阻止

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://24.151.51.34:3000/socket.io/?EIO=3&transport=polling&t=1437399007343-0. (Reason: CORS request failed). 

我已經用代碼瞎搞在開始自己的項目之前找到解決這個問題的希望,但我不能想出一個辦法。客戶端代碼是:

<!doctype html> 
<html> 
    <head> 
    <title>Socket.IO chat</title> 
    <style> 
     * { margin: 0; padding: 0; box-sizing: border-box; } 
     body { font: 13px Helvetica, Arial; } 
     form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } 
     form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } 
     form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } 
     #messages { list-style-type: none; margin: 0; padding: 0; } 
     #messages li { padding: 5px 10px; } 
     #messages li:nth-child(odd) { background: #eee; } 
    </style> 
    </head> 
    <body> 
    <ul id="messages"></ul> 
    <form action=""> 
     <input id="m" autocomplete="off" /><button>Send</button> 
    </form> 
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> 
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script> 
    <script> 
     var socket = io('24.151.51.34:3000'); 
     $('form').submit(function(){ 
     socket.emit('chat message', $('#m').val()); 
     $('#m').val(''); 
     return false; 
     }); 
     socket.on('chat message', function(msg){ 
     $('#messages').append($('<li>').text(msg)); 
     }); 
    </script> 
    </body> 
</html> 

對於服務器代碼,我嘗試添加代碼,讓CORS,但真的不知道該怎麼做:

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

io.set('origins', 'http://browsercombat.com:80'); 

app.use(function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS"); 
    res.header("Access-Control-Allow-Credentials", "true"); 
    next(); 
}); 

app.get('/', function(req, res, next) { 
    res.sendFile(__dirname + '/index.html'); 
}); 

app.post('/', function(req, res, next) { 
    // Handle the post for this route 
}); 

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

http.listen(3000, function(){ 
    console.log('listening on *:3000'); 
}); 
+0

myip是什麼? – Bergi

+0

啊,忘了提及我是連接到我的ip的端口轉發,我決定用「myip」替換它。 – uncoded

+0

Express和socket.io的CORS代碼示例:http://enable-cors.org/server_expressjs.html和http://stackoverflow.com/questions/24058157/socket-io-node-js-cross-origin-請求攔截。 – jfriend00

回答