【问题标题】:CORS issue on socket.iosocket.io 上的 CORS 问题
【发布时间】:2017-04-19 22:54:01
【问题描述】:

我正在尝试从这里的this 教程学习 socket.io。但问题是我无法让应用程序运行。这是我得到的错误:

XMLHttpRequest 无法加载 http://127.0.0.1:3000/socket.io/?EIO=3&transport=polling&t=LZFI7Tq。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此,Origin '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');

我已经浏览了几篇与此问题相关的帖子,但无法解决。请帮帮我。

【问题讨论】:

  • 您需要启用 CORS。在您的服务器代码中添加res.setHeader("Access-Control-Allow-Origin", "*");
  • 在服务器端尝试const io = require('socket.io')(3000);(删除第二行)和在客户端尝试var socket = io();
  • @BidhanA,我已经用我所有的服务器端代码更新了这个问题。我不明白该在哪里插入该标题。
  • @mk12ok 在将代码更改为您建议的内容后,cors 问题消失了,但我得到了这个GET http://localhost/socket.io/?EIO=3&transport=polling&t=LZFN0DQ 404 (Not Found) universalModuleDefinition:2
  • 您必须在127.0.0.1:3000 上运行某种服务器才能使其正常工作。本教程假设您已经设置了服务器(我认为您没有)。查看“更新!”部分来设置您自己的服务器。

标签: javascript node.js sockets socket.io


【解决方案1】:

在创建 cookie 的服务器上添加此中间件

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();
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2021-04-10
    • 2020-06-29
    • 1970-01-01
    • 2021-12-26
    • 2021-08-06
    • 2021-08-05
    相关资源
    最近更新 更多