简体   繁体   English

为什么 CORS 在将 SocketIO 与 Express 和 React 一起使用时被阻止

[英]Why CORS is blocked when using SocketIO with Express and React

I am trying to develop a simple chat app using Node, React, Express & Socket.io.我正在尝试使用 Node、React、Express 和 Socket.io 开发一个简单的聊天应用程序。

Here is my Node server set up:这是我的节点服务器设置:

const express = require("express");
const cors = require('cors');
const http = require('http');
const socketio = require('socket.io');

// ENV VARS
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

const SERVER_PORT = process.env.SERVER_PORT || 5000;
const HOST = process.env.HOST || "http://localhost";

// INIT
const app = express();
const server = http.createServer(app);
const io = socketio(server);

// MIDDLEWARE
app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());

io.on('connection', (socket) => {
  console.log('new client connected');
});

// ON LISTEN
server.listen(SERVER_PORT, () => {
  console.log(`app listening at ${HOST}:${SERVER_PORT}`);
});

Here is my client side:这是我的客户端:

import {io} from "socket.io-client";
  
import './App.css';

const PORT = 5000
const HOST = "http://localhost"
const SERVER_URL = HOST + ':' + PORT
console.log(SERVER_URL);

function App() {
  let socket = io(SERVER_URL);
  return (
    <div className="App">
      aaaa
    </div>
  );
}

export default App;

I simply tried to test the on connection event, Yet I am getting the following error:我只是尝试测试连接事件,但出现以下错误:

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 策略已阻止从源“http://localhost:3000”在“http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt”访问 XMLHttpRequest:否“访问控制”- Allow-Origin' header 存在于请求的资源上。

polling-xhr.js:203 GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt net::ERR_FAILED polling-xhr.js:203 GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt net::ERR_FAILED

i tried adding:我尝试添加:

{origins: '*'}

as socket io doc says but the errors are still showing.正如套接字 io 文档所说,但错误仍然存在。 What am I doing wrong?我究竟做错了什么?

I think changing the order of initialization could help, because your server lacks all the middleware applied to app .我认为更改初始化顺序可能会有所帮助,因为您的server缺少应用于app的所有中间件。

// INIT
const app = express();

// MIDDLEWARE
app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());

// Create server and listen on PORT after adding middleware
const server = app.listen(PORT, () => {
  console.log(`app listening at ${HOST}:${SERVER_PORT}`)
});

// Try to avoid wilcard ('*') origins
const io = socketio(server, { cors: { origin: '*' } });

// Handle socketio connections
io.on('connection', (socket) => {
  console.log('new client connected');
});

// EOF

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM