【问题标题】:Node Js - Identify if the request is coming from mobile or non-mobile deviceNode Js - 识别请求是来自移动设备还是非移动设备
【发布时间】:2020-08-28 15:51:52
【问题描述】:

我还是 node js 的新手。是否有任何解决方法或方法可以识别来自客户端的请求是来自使用节点 js 的移动设备还是非移动设备?因为我现在正在做的是我想根据设备类型(移动/桌面)限制对某些 API 的访问。我在服务器端使用restify。谢谢。

【问题讨论】:

标签: javascript node.js restify


【解决方案1】:

@H.Mustafa,检测客户端是否使用移动设备的基本方法是匹配userAgent 中的一组特定字符串。

function detectMob() {
    const toMatch = [
        /Android/i,
        /webOS/i,
        /iPhone/i,
        /iPad/i,
        /iPod/i,
        /BlackBerry/i,
        /Windows Phone/i
    ];

    return toMatch.some((toMatchItem) => {
        return navigator.userAgent.match(toMatchItem);
    });
}

(参考:Detecting a mobile browser

在客户端的设备上运行这个 sn-p 的代码。如果返回的结果是true,您就知道它是移动设备,或者是台式机/笔记本电脑。希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我建议的方法是使用 npm 包express-useragent,因为从长远来看更可靠。

    var http = require('http')
      , useragent = require('express-useragent');
     
    var srv = http.createServer(function (req, res) {
      var source = req.headers['user-agent']
      var ua = useragent.parse(source);
      
      // a Boolean that tells you if the request 
      // is from a mobile device
      var isMobile = ua.isMobile
    
      // do something more
    });
     
    srv.listen(3000);
    

    它也适用于 expressJS:

    var express = require('express');
    var app = express();
    var useragent = require('express-useragent');
     
    app.use(useragent.express());
    app.get('/', function(req, res){
        res.send(req.useragent.isMobile);
    });
    app.listen(3000);
    

    【讨论】:

    • 如果使用 Typescript,请确保在您的包中导入 @types/express-useragent,以便正确扩展 Request 类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多