Socket.io Express Http-Server 后端,CORS 错误

Posted

技术标签:

【中文标题】Socket.io Express Http-Server 后端,CORS 错误【英文标题】:Socket.io Express Http-Server Backend, CORS error 【发布时间】:2022-01-14 21:20:39 【问题描述】:

我正在开发一个使用 express 作为后端的应用程序。然后我想为一些实时聊天功能添加 socket.io。一切都在邮递员上运行得非常好,但是当我的前端反应代码使用反应查询进行 get req 时,我得到一个 cors 错误。

在我用http-server实现socket.io相关代码之前,没有这个问题。

免责声明:我已经查看了类似问题的解决方案,我确实需要使用 express,而我看到的所有解决方案都只是针对基于 http-server 的应用程序。

这里有一些代码:

后端:

require("dotenv").config();
const PORT = process.env.PORT;

const express = require("express");
const cors = require("cors");
const 
  createServer
 = require("http");
const 
  Server
 = require("socket.io");

const 
  accountRouter,
  chatRouter,
  commentRouter,
  searchRouter,
  authRouter,
 = require("./Routes");

const WebSocketService = require("./Services/WebSocketService");

const 
  connection
 = require("./Services/Database");
connection();

const app = express();
const httpServer = createServer(app);

const io = new Server(httpServer, 
  cors: 
    origin: "http://localhost:3000",
    methods: ["GET", "POST", "DELETE"]
  ,
);

const onConnection = (socket) => 
  console.log(`User socketId: $socket.id connected`)
  WebSocketService(io, socket);
;

io.on("connection", onConnection);

app.use(cors());
app.use(express.json());
app.use(express.urlencoded(
  extended: true
));

app.use("/unis", searchRouter.unisRouter);
app.use("/courses", searchRouter.coursesRouter);
app.use("/files", searchRouter.fileRouter);

app.use("/comments", commentRouter);
app.use("/chats", chatRouter);
app.use("/account", accountRouter);

app.use("/signup", authRouter.signupRouter);
app.use("/login", authRouter.loginRouter);
app.use("/admin", authRouter.adminRouter);

httpServer.listen(PORT, () => 
  console.log(`Server ready at $process.env.PUBLIC_URL:$PORT`);
);

前端:

import React, 
  useEffect,
  useState
 from "react";
import "./styles.scss";

import axios from "axios";
import 
  useQuery
 from "react-query";

const fetchAllUnis = async() => 
  const 
    data
   = await axios.get("localhost:4000/unis");
  return data;
;

export const Unis = (
  ViewComponent,
  activeClass,
  BreadCrumbData,
  SetBreadCrumbData,
) => 
  const 
    data,
    error,
    isLoading,
    isError
   = useQuery("unis", fetchAllUnis);

  return ( <
    div className = 
      activeClass === "grid" ? "unis grid" : "unis"
     > 
      data &&
      data.map(
        (
          _id: itemID,
          uniName: itemName,
          uniLogoPath: itemLogoPath,
          uniCourses,
        ) => ( <
          ViewComponent key = 
            itemID
          
          props = 
            
              itemID,
              itemName,
              itemLogoPath,
              itemType: "uni",
              courseCount: uniCourses.length,
            
          
          />
        )
      )
     <
    /div>
  );
;

【问题讨论】:

什么是 cors 错误? const io = new Server(httpServer, cors: origin: "localhost:3000", methods: ["GET", "POST", "DELETE"] , );我认为你必须改变 cors: origin: "localhost:3000", methods:"*" // OR for all methods , 【参考方案1】:

原来我需要 crossdomain: true 作为 axios 调用的选项。

const fetchAllUnis = async() => 
  const 
    data
   = await axios.get("localhost:4000/unis", crossdomain: true);
  return data;
;

【讨论】:

以上是关于Socket.io Express Http-Server 后端,CORS 错误的主要内容,如果未能解决你的问题,请参考以下文章

未找到 Socket.io.js(node.js + express + socket.io)

我的 socket.io 设置为 express 不工作

socket.io 和 express 4 个会话

如何使用 Socket.io 和 Express 进行集群

没有 express.js 的 Socket.io 会话?

如何在express的路由中操作socket.io