【问题标题】:How socket.io can be used like axios?socket.io 怎么能像 axios 一样使用?
【发布时间】:2021-12-23 04:51:30
【问题描述】:

我有一个应用程序,它内置在 axios 中,只考虑 PUT、POST、DELETE、GET。看起来像这样

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

          })
  }

还可以使用不同的方法执行“post/”、“logout/”、“signup/”。 后来我发现,为了在客户端实时发布动作,我们需要使用 websocket。所以我使用了 socket.io 。 我已经设置了服务器和客户端。

在这样的服务器套接字连接中

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

在客户端连接中,我搜索了教程并使用了 contextAPI,并传递给了所有组件。 在我的特定组件中,我已经发布了用户帖子,并且显示了用户帖子我已经放置了这样的代码

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

现在我如何使用带有捕获错误但带有 socket.io 的 axios 请求。使用与 axios 集成的 socket.io 对我来说似乎很难。虽然我不需要在身份验证时使用套接字。但我需要在“/post”请求中使用它。

通过 axios.POST.then().catch(), axios.GET ...... 但我很困惑将 axios 的东西集成到客户端的套接字中。

在后端,我也有这样的路线

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

每个处理程序都像这样

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)
  })
}

但是如果我想使用socket.io,我应该怎么做?我对 socket.io 文档感到非常困惑,没有显示用于处理事情。

如果你对这些事情有想法, 请回答我谢谢你的回答

【问题讨论】:

    标签: javascript reactjs sockets socket.io axios


    【解决方案1】:

    Socket.io 保持其连接处于活动状态。为了处理错误。您将需要收听事件。例如: 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
    });
    

    如果您想确保您的服务器端处理您的请求并需要确认,您可以使用可选的“确认”功能,例如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");
        });
      });
    

    【讨论】:

      猜你喜欢
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多