首页 > 解决方案 > Node + vue js 用户离线/在线状态(服务器端)

问题描述

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

我将如何做到这不是 PHP 而不是套接字 io,因为我相信某些防火墙会阻止套接字 io 连接,这会破坏我的应用程序。

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

标签: node.jsvue.js

解决方案


好吧,既然你不想使用套接字,那么你的用户表应该有一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
});

推荐阅读