最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked May 12, 2020 at 17:19 DMDJDMDJ 4072 gold badges7 silver badges14 bronze badges 2
  • You could use an npm package to grab detailed information for each device that visits your website - npmjs.com/package/bowser – goto Commented May 12, 2020 at 17:33
  • Check this link stackoverflow.com/a/22286027/8159775, it should help! – Alex K - JESUS first Commented Feb 26, 2021 at 12:06
Add a comment  | 

2 Answers 2

Reset to default 10

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

@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.

发布评论

评论列表(0)

  1. 暂无评论