node.js - Node + vue js 用户离线/在线状态(服务器端)
问题描述
我希望能够查看用户当前是否正在浏览该网站。我知道您可以检测用户是否离线/在线客户端,但我想监控他们是否在线并显示状态消息/颜色。
我将如何做到这不是 PHP 而不是套接字 io,因为我相信某些防火墙会阻止套接字 io 连接,这会破坏我的应用程序。
我使用 vue js 和 node 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
});
推荐阅读
- .net-core - How to setup .Net Core NUnit testing with Azure Pipelines
- java - Compilation error when instantiating object
- python - 如何仅计算组中第一个值的差异?
- c# - 如何使用uribuilder获取目录下的所有子目录
- python - 为什么我的旋转图像没有正确保存?
- java - 在自定义 Java AWS 应用程序中找不到类的序列化程序
- flutter - Dart - 强制一个类有一个工厂
- vb.net - 使用 ADODB 从查询中检索值
- python - Python 串行通信脚本问题(在 Visual Studio 中)
- mysql - 从列中搜索逗号分隔的值包含逗号分隔的字符串mysql