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
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
-
Change on client
const socket = io('http://localhost:8000'); console.log(socket);
– zemmsoares Commented Apr 3, 2019 at 16:31
2 Answers
Reset to default 6havn't really ran the code; but, did you notice the port in the error is 3000 rather than 8000 which you initialized the server to listen on?
reading https://socket.io/docs/client-api/, it says that the default is the window location, knowing react, you probably running on port 3000, which is the same 3000 in the error
try setting the port when initializing the socket object
const socket = io("localhost:8000");
Below is the code for connecting through socket if you want that after page is rendered then your socket get connected then write it in ponentDidMount.
import React, { Component } from "react"
import io from "socket.io-client"
import "./App.css";
class App extends Component {
ponentDidMount(){
let socket = io.connect("http://localhost:8000");
console.log(socket)
}
render() {
return (
// ...
)
}
}
export default App
For example you can go through the link : https://medium.freecodecamp/how-to-create-a-realtime-app-using-socket-io-react-node-mongodb-a10c4a1ab676
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745130618a4612952.html
评论列表(0条)