首页 > 解决方案 > Use socket.io with React

问题描述

How do I use socket.io with React? I have this code for my client:

import React, { Component } from "react"
import io from "socket.io-client"
import "./App.css"

const socket = io()
console.log(socket)

class App extends Component {
    render() {
        return (
            // ...
        )
    }
}

export default App

And for my server:

const express = require("express"),
    app = express(),
    http = require("http").Server(app),
    io = require("socket.io")(http)

io.on("connection", socket => {
    console.log("New connection")
})

http.listen(8000, () => {
    console.log("Started!")
})

But I keep getting this error:

POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MdZyD8L 404 (Not Found)

What did I do wrong? Thanks.

PS: To launch the app, I do npm run start, and for the server node server/server.js

标签: javascriptreactjssocket.io

解决方案


还没有真正运行过代码;但是,您是否注意到错误中的端口是3000而不是您初始化服务器以侦听的8000 ?

阅读https://socket.io/docs/client-api/,它说默认是窗口位置,知道反应,你可能在端口 3000 上运行,这与错误中的 3000 相同

初始化套接字对象时尝试设置端口

const socket = io("localhost:8000");

推荐阅读