无法解决 React & SOCKET.IO CORS 错误

Seb*_*030 6 node.js socket.io reactjs

我试图设置一个非常简单的应用程序以熟悉在 React 应用程序中使用 SOCKET.IO。服务器看起来像这样:

const io = require('socket.io')();

io.origins('*:*');

io.on('connection', (client) => {
  client.on('subscribeToTimer', (interval) => {
    console.log('client is subscribing to timer with interval ', interval);
    setInterval(() => {
      client.emit('timer', new Date());
    }, interval);
  });
});

const port = 8000;
io.listen(port);
console.log('listening on port ', port);
Run Code Online (Sandbox Code Playgroud)

使用 Create-React-App 设置的 React Client 如下所示:

import React, { Component } from 'react';
import './App.css';
import openSocket from 'socket.io-client';
const socket = openSocket('http://localhost:8000');


function subscribeToTimer(cb) {
  socket.on('timer', timestamp => cb(timestamp));
  socket.emit('subscribeToTimer', 1000);
}

class App extends Component {
  constructor(props) {
    super(props);

    subscribeToTimer((timestamp) => {
      this.setState({
        timestamp
      });
    });
  }

  state = {
    timestamp: 'no timestamp yet'
  };

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <h2>Our awesome drawing app</h2>
        </div>
        This is the value of the timer timestamp: {this.state.timestamp}      
      </div>
    );
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

所以基本上服务器使用 socket.io 向客户端发送时间戳,然后这个 get's 每秒反映在那里。但是,此设置遇到了以下 CORS 问题:

localhost/:1 无法加载 http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MEwUo-e : 重定向自 ' http://localhost:8000/socket.io/?EIO=3&transport= polling&t=MEwUo-e ' to ' https://localhost:8443/socket.io/?eio=3&transport=polling&t=MEwUo-e ' 已被 CORS 策略阻止:没有 'Access-Control-Allow-Origin' 标头是出现在请求的资源上。因此,不允许访问Origin ' http://localhost:3000 '。

我检查了其他问题中提供的所有解决方案,即io.origins{*:*},我尝试使用 express.js 和 cors npm 包等进行相同的操作,但错误仍然存​​在。知道我在这里做错了什么吗?我正在使用 Chrome 浏览器。非常感谢提前

Seb*_*030 16

好的,我终于在这里找到了解决方案:https : //github.com/socketio/socket.io-client/issues/641 这导致我将第 4 行的客户端代码更改为const socket = openSocket('http://localhost:8000', , {transports: ['websocket']});


HOS*_*NUR 8

用这个 :

const server = app.listen('3001', () => {
    console.log("Server Up")});

    const io = socket(server, {
        cors: {
            origin: "http://localhost:3000",
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 您能为您的答案添加更多解释吗?你的代码有什么作用以及它将如何帮助OP? (3认同)