Node Js - 确定请求是来自移动设备还是非移动设备

H.M*_*afa 5 javascript node.js restify

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

Joã*_*ira 9

我建议的方法是使用 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);
Run Code Online (Sandbox Code Playgroud)

它也适用于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);
Run Code Online (Sandbox Code Playgroud)

  • 看来“ua-parser-js”现在是解析用户代理字符串的标准库。到目前为止,“express-useragent”已经 3 年没有更新了。https://www.npmjs.com/package/ua-parser-js (2认同)

Mel*_*ham 5

@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);
    });
}
Run Code Online (Sandbox Code Playgroud)

(参考:检测移动浏览器

在客户端设备中运行这段代码。如果返回的结果是true,则您知道它是移动设备,而不是台式机/笔记本电脑。希望这可以帮助。