Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

359
Visualizações
How socket.io can be used like axios?

I've an application, which is built in axios, just PUT, POST, DELETE, GET in mind. which looks like this

getAPI = axios.create(.....)
....
getAPI.post('signup/', {email, password})
          .then(res => {
          /// return some res
          })
          .catch(err => {
          /// some error is show if not succeed

          })
  }

and also goes or "post/", "logout/", "signup/" with different methods. Later i found that, In order to make post actions realtime in client side , we need to use websocket. So i used socket.io . I've already setup server and client.

In server socket connection like this

io.on('connection', socket => {
    console.log('User is connected on socket');
    socket.on('disconnect', () => console.log('disconnected'));
})

and in client connection i've searc tutorials and used contextAPI, and passed to allcomponents. in my specific component, where i've user post and user post is shown i've put code like this

  const {socket} = useContext(AuthContext);
  useEffect(() => {
    socket.on("connect", () => {
    console.log("client connected")
  })
    return ()=> socket.disconnect()
  })

Now how can i use those of axios request with catch errors but with socket.io. It seems very hard to me using socket.io integrating with axios . Although i need not to use socket on authentication. But i need to use it on "/post" request.

Posting from client to server was easy by that axios.POST.then().catch(), axios.GET ..... but i'm confused to integrate that axios things in socket in client .

Also in backend side , i've routes like these

router.get('/logout', logout)
router.post('/post/create', post)

with each handler like these

exports.postCreate = (req, res) => {
  let post =   new Post(req.body)
  post.save((err, post) => {
    if(err){
      return res.status(400).json({error: "Error"})
    }
  return res.json(post)
  })
}

but if i want to use socket.io, what should i do? I'm very confused by socket.io docs, not showing for handeling things.

If you have idea about these things, please answer me Thank you for your answer

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Socket.io keeps its connections alive. In order to handle errors. You will need to listen to events. For example: Handling connection errors:

socket.on("connect_error", (error) => {
  // ...
});

Handling disconnect errors:

socket.on("disconnect", (reason) => {
  if (reason === "io server disconnect") {
    // the disconnection was initiated by the server, you need to reconnect manually
    socket.connect();
  }
  // else the socket will automatically try to reconnect
});

If you'd like to ensure that your server side handled your request and need confirmation you can use the optional 'ack' feature like this:

// client side
socket.emit("ferret", "tobi", (data) => {
  console.log(data); // data will be "woot"
});

// server side:
  io.on("connection", (socket) => {
    socket.on("ferret", (name, fn) => {
      fn("woot");
    });
  });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda