Node Js - Identify if the request is coming from mobile or non-mobile device

↘锁芯ラ 提交于 2021-01-28 03:54:09

问题


I'm still new with node js. Is there any workaround or methods on how to identify the request from client-side is from mobile or non-mobile devices using node js? Because what i'm doing now is i want to restrict the access on certain API based on the device type (mobile / desktop). I'm using restify for the server-side. Thanks.


回答1:


@H.Mustafa, a basic way to detect if a client is using a mobile device is by matching a particular set of strings in the 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);
    });
}

(Reference: Detecting a mobile browser)

Run this snippet of code in client's device. If the returned result is true, you know it's a mobile device else a desktop/laptop. Hope this helps.




回答2:


The method I'd suggest is to use the npm package express-useragent since is more reliable over the long term.

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);

It also works with 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);


来源:https://stackoverflow.com/questions/61757942/node-js-identify-if-the-request-is-coming-from-mobile-or-non-mobile-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!