小编Seb*_*030的帖子

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

我试图设置一个非常简单的应用程序以熟悉在 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 …
Run Code Online (Sandbox Code Playgroud)

node.js socket.io reactjs

6
推荐指数
2
解决办法
1万
查看次数

标签 统计

node.js ×1

reactjs ×1

socket.io ×1