带有cloudflare跨源错误的Socket.io 525

时间:2018-03-09 13:43:11

标签: node.js reactjs websocket socket.io cloudflare

我有一个应用程序,我们尝试在节点上使用socket.io实现通知并做出反应。这是节点应用程序:

const app = require('express')();
const http = require('http').Server(app);
const redis = require('redis');
const client = redis.createClient();
const server = redis.createClient();
const io = require('socket.io').listen(http);

const redisClients = [
    'demo'
];

const socketPort = 2053;
const cors = require('cors');

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

redisClients.forEach(c => client.subscribe(c));

client.on("message", function (channel, message) {
    console.log(`${channel} '----' ${message}`)
    var info = JSON.parse(message);
    io.sockets.emit(channel, info);
});

io.on("connection", function(socket) {
    console.log("connected socket")

    redisClients.forEach((client) => {
        socket.on(client, function (msg) {
            console.log(`from client  ` + JSON.stringify(msg))
            server.publish(`${client}-server`, JSON.stringify(msg));
        });
    })

    socket.on("disconnect", function () {
        console.log("client disconnected")
        socket.disconnect();
    });
});

http.listen(socketPort);

在本地客户端应用程序中,我们测试了一些随机端口,如7000等,代码工作正常。部署到服务器时,我们必须将端口更改为2053,这是为安全ssl通信打开的端口之一。 ssl证书由cloudflare管理(免费层:灵活的ssl)。以下是反应中的客户端代码:

import io from 'socket.io-client';
const socket = io('https://my-domain.com:2053', {
  secure: true,
  reconnect: true
});
class App extends Component {
componentWillMount() {
      socket.on(appName, data => {
        const userNotification = filterUserNotification(
          data,
          String(this.props.userSession.id)
        );
        if (userNotification)
          this.props.dispatch(updateNotifications([userNotification]));
      });
}

我得到的错误如下:

无法加载https://my-domain.com:2053/socket.io/?EIO=3&transport=polling&t=M8AzArB:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源' https://my-domain.com'因此不允许访问。响应的HTTP状态代码为525.

有人可以帮我弄清楚这里出了什么问题。

0 个答案:

没有答案