react客户端:WebSocket.js:83 WebSocket连接到“ws://localhost:3009/socket.io/?EIO=4&transport=WebSocket'失败:

o8x7eapl  于 2023-10-20  发布在  React
关注(0)|答案(2)|浏览(145)

我有一个使用套接字IO的节点后端
first in app.js initialize初始化应用

const express = require("express")

const app = express()

module.exports = {
    app,
    express
}

然后在io.js中,我创建socket服务器,

const { app } = require("./app");
const http = require("http");
const socketio = require("socket.io");
const server = http.createServer(app);
const io = socketio(server);

module.exports = io;

然后在server.js中,首先导入用于API调用的app.js,然后导入io.js

require("dotenv").config();
const { app, express } = require("./app");
const logger = require("./logger");

const io = require("./io");

然后在server.js中添加emit listen代码

io.on("connection", (socket) => {
  console.log("we have a new connection");

  socket.on("disconnect", () => {
    console.log("the socket disconnected");
  });

  socket.on("join", ({ user_id }, callback) => {
    // const notification = getListNotifications(user_id);
    // const popup = getUserPopup(user_id);
    // socket.emit("nofication", { popup: popup.count, notification });
    socket.emit("nofication", { popup: 3, notificaton: { a: 1 } });
    socket.join(user.room);
    callback();
  });

然后我在开发模式下运行server.js文件nodemon server.js
然后在react中,我简单地使用socket.io

import io from "socket.io-client";

useEffect(() => {
    socket = io("ws://localhost:3009", {
      "force new connection": true,
      reconnectionAttempts: "Infinity",
      timeout: 10000,
      transports: ["websocket"],
    });

   

    return () => {
      socket.disconnect();
    };
  }, []);

它给了我这个错误在浏览器控制台

服务器node.js控制台正在接收https协议

我在其他答案中发现,这可能是一些协议问题。
很高兴向你学习。Thanks in advance

agxfikkp

agxfikkp1#

发生在我身上,我正在听服务器与应用程序。听只接收https协议..但我已经创建了一个单独的ws服务器与服务器变量,应该听一个端口,使服务器可以接收ws连接.
更好地使用这个库npm link将使工作更容易.

koaltpgm

koaltpgm2#

您可以将下面的代码行添加到index.js文件中

const chatServer = require('http').Server(app);
const chatSockets = require('./config/chat_sockets').chatSockets(chatServer);

 and below lines of code to you config--> sockets.js

module.exports.chatSockets = function(socketServer){
   
    let io = require("socket.io")(socketServer, {
        cors: {
          origin: "http://localhost:8000",
          methods: ["GET", "POST"],
        }
      });

相关问题