2016-12-05 98 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(); 
})