【问题标题】:how to determine a client operating system in Node.js如何在 Node.js 中确定客户端操作系统
【发布时间】:2018-09-19 23:35:39
【问题描述】:

我正在尝试在登录过程中在我的应用程序中实现 2FA,我希望向他们发送登录请求所来自的操作系统和设备的名称,但我已尝试四处寻找解决方案来确定这个,我发现的只是后端(nodejs os模块)。是否有任何 npm 模块或方法可供我存档。

【问题讨论】:

    标签: node.js npm


    【解决方案1】:

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

    【讨论】:

    • 谢谢,但它不能在服务器端代码上运行,它只能在前端运行。我正在寻找可以在后端使用的东西。 :)
    • 不,它也适用于服务器端,请正确阅读文档
    【解决方案2】:

    我希望向他们发送登录请求所在的国家/地区 来自

    IMO,这可以/应该在服务器端确定(使用 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}`);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-11
      • 2011-06-24
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      相关资源
      最近更新 更多