如何在Node.js中确定客户端操作系统

3

我正在尝试在登录过程中为我的应用程序实现双重身份验证,并希望向用户发送发起登录请求的操作系统和设备名称,但是我已经尝试搜索了解决此问题的方法,但我找到的只适用于后端(nodejs os模块)。是否有任何npm模块或其他方式可以帮助我实现这一目标。

2个回答

4
使用Sniffr包从请求头中获取user-agent信息...

enter image description here


谢谢,但它不能在服务器端代码上运行,只能在前端工作。我正在寻找可以在后端使用的东西。 :) - Fillipo Sniper
不,它也可以在服务器端工作,请正确阅读文档。 - Tilak Putta

2
我希望发送一个国家的信息,该信息来自登录请求。
在我看来,这应该可以在服务器端确定(使用类似 node-geoip 的工具)。
至于检测客户端操作系统,您需要解析 User-Agent 请求头。Tilak Putta 建议使用的模块也可以在后端使用。

例子:

const http = require('http');

const geoip = require('geoip-lite'); // npm install --save geoip-lite -- have a look at https://github.com/bluesmoon/node-geoip to know how to update the datafiles
const Sniffr = require("sniffr"); // npm install --save sniffr
const requestIp = require('request-ip'); // npm install --save request-ip

const HOST = process.env.HOST || '0.0.0.0';
const PORT = process.env.PORT || 1337;

const server = http.createServer((req, res) => {
  const userAgent = req.headers['user-agent'];
  const s = new Sniffr();
  s.sniff(userAgent);

  const clientIp = requestIp.getClientIp(req);
  const geo = geoip.lookup(clientIp); // will be set to null if server is accessed locally

  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.end(JSON.stringify({
    ...s,
    clientIp,
    geo
  }, null, 2));
});

server.listen(PORT, HOST, () => {
    console.log(`Server is listening on http://${HOST}:${PORT}`);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接