【问题标题】:Node + vue js user offline/online status(server side)Node + vue js 用户离线/在线状态(服务器端)
【发布时间】:2020-06-16 10:34:31
【问题描述】:

我希望能够查看用户当前是否正在浏览该网站。我知道您可以检测用户是否离线/在线客户端,但我想监控他们是否在线并显示状态消息/颜色。

如果不是 PHP 而不是 socket io,我该怎么做,因为我相信某些防火墙会阻止 socket io 连接,这会破坏我的应用程序。

我使用 vue js 和 node js 并想检测用户当前是否正在浏览并在服务器端使用它。我发现的其他解决方案是设置超时,但如何针对用户而不是服务器?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 发布你的代码,你到目前为止为后端和前端编写的代码
  • @rags2riches 还没有
  • @AhmedKhattab 代码只是 jwt 身份验证和加载数据。在这种情况下没有任何用处

标签: node.js vue.js


【解决方案1】:

好吧,既然你不想使用套接字,那么你的用户表应该有一个is_active 列。在前端,在您的应用程序的入口点,您调用您的 api 将活动状态设置为 1,这意味着它们在线。

您的后端控制器可能是这样的,使用 express

const app = express();

app.post('/users/active-status/:id', (req, res, next) => {
   const userId= req.params.id;
   const status = req.params.activeStatus

  // then find the user and set the is_active status to status variable

  next();
});


在您的前端,您可以监听关闭事件、函数并将用户活动状态设置为 0

你的根组件


// when the user enters the website he is active
axios.post('/users/active-status/'+ userId, {
    activeStatus: 1
});


// check before they leave and set the active status to 0
window.onclose= function (e) {
    axios.post('/users/active-status/'+ userId, {
       activeStatus: 0
    });
};



window.addEventListener('offline', function(event){
    // the user has lost connection here
});

【讨论】:

  • 谢谢,如果他们突然失去连接或其他什么,我将如何实施检查?
  • 可以通过js在线和离线事件监听vue js内部的网络事件
  • 我现在已将其包含在我的答案中,如果这解决了您的问题,请投票,祝您编码愉快
猜你喜欢
  • 2015-05-13
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2016-07-09
相关资源
最近更新 更多