2016-12-05 53 views
0

我想從this教程這裏學習socket.io。但問題是我無法讓應用程序運行。這是我得到的錯誤:CORS問題socket.io

的XMLHttpRequest無法加載 http://127.0.0.1:3000/socket.io/?EIO=3&transport=polling&t=LZFI7Tq。否 「訪問控制 - 允許來源」標題出現在請求的 資源中。因此不允許訪問原產地'http://localhost'。 響應了HTTP狀態代碼404

這是服務器端的連接

var io = require('socket.io'); 
var socket = io.listen(3000, '127.0.0.1'); 

// all the people that have joined the chat 
var people = {}; 

socket.on('connection', function (client) { 
    console.log('An user connected'); 
    client.on('join', function(name) { 
     people[client.id] = name; 

     // client.emit() will only update the client that you are looking 
     // at, whereas socket.sockets.emti() will update all connected clients 
     client.emit('update', 'You have successfully connected..'); 
     socket.sockets.emit('update', name + " has joined the conversation.."); 
     socket.sockets.emit('update-people', people); 
    }); 

    client.on('send', function(msg){ 
     socket.sockets.emit('chat', people[client.id], msg); 
    }); 

    client.on('disconnect', function() { 
     socket.sockets.emit('update', people[client.id] + ' has left the conversation..'); 
     delete people[client.id]; 
     socket.sockets.emit('update-people', people); 
    }); 

}); 

這是客戶端連接

var socket = io.connect('http://127.0.0.1:3000'); 

我已經通過相關的幾個職位這個問題,但無法解決它。請幫幫我。

+1

您需要啓用CORS在服務器上。在您的服務器代碼中添加'res.setHeader(「Access-Control-Allow-Origin」,「*」);'。 –

+0

在客戶端嘗試'const io = require('socket.io')(3000);'在服務器端(刪除你的第二行)和'var socket = io();' – mk12ok

+0

@BidhanA,所有我的服務器端代碼的問題。我不明白我在哪裏插入該標題。 –

回答

1

添加這個中間件在那裏你的cookies創建

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-Type'); 
    res.header('Access-Control-Allow-Credentials', 'true'); 
    next(); 
})