javascript - 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
解决方案
还没有真正运行过代码;但是,您是否注意到错误中的端口是3000而不是您初始化服务器以侦听的8000 ?
阅读https://socket.io/docs/client-api/,它说默认是窗口位置,知道反应,你可能在端口 3000 上运行,这与错误中的 3000 相同
初始化套接字对象时尝试设置端口
const socket = io("localhost:8000");
推荐阅读
- javascript - 为什么 Nuxt 不转译 vendor.app.js?
- r - 在 stringr 中使用 perl/regex 到上层 \U
- javascript - 如何突出显示替换文本的所有实例
- c# - 需要简单、强大的 c# 解决方案来动态解析和缩短 Uri 字符串
- d - 接口和模板函数
- r - 使用 rdrobust 包在 R 中使用协变量拟合回归不连续模型
- excel - VBA将日期和时间的列转为24小时(Excel)
- python-3.x - 计算两个熊猫列之间向量的余弦相似度?
- elasticsearch - 使用 logstash 解析 json 数组字符串
- docker - 将 Kubernetes pod 限制为一个进程