2

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

1
  • Change on client const socket = io('http://localhost:8000'); console.log(socket); Commented Apr 3, 2019 at 16:31

2 Answers 2

6

havn'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");
Sign up to request clarification or add additional context in comments.

1 Comment

Also. be sure to not hardcode it to localhost:8000 when deploying (if doing so) it. I had this and I deployed my app to heroku.. I then found out that there were no connections to my server... because i had it hardcode it to localhost from the client... if you just do io() it will "autoconnect to the window's location" socket.io/docs/client-api
0

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 componentDidMount.

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

class App extends Component {

componentDidMount(){
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.org/how-to-create-a-realtime-app-using-socket-io-react-node-mongodb-a10c4a1ab676

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.