Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Express中使用正则表达式进行用户代理嗅探的失败率为50%?_Javascript_Node.js_Regex_Express - Fatal编程技术网

Javascript 在Express中使用正则表达式进行用户代理嗅探的失败率为50%?

Javascript 在Express中使用正则表达式进行用户代理嗅探的失败率为50%?,javascript,node.js,regex,express,Javascript,Node.js,Regex,Express,我在express router中定义了一个正则表达式,以确定UA是否是移动的,并根据它是否是移动的,呈现不同的页面 在我们的生产现场进行测试后,其故障率为25%-50% 我想知道根本原因和解决办法 多谢各位 Index.js const moment = require('moment'); var _ = require('lodash'); var mobileRegex = new RegExp(/(android|bb\d+|meego).+mobi

我在express router中定义了一个正则表达式,以确定UA是否是移动的,并根据它是否是移动的,呈现不同的页面

在我们的生产现场进行测试后,其故障率为25%-50%

我想知道根本原因和解决办法

多谢各位

Index.js

  const moment = require('moment');
        var _ = require('lodash');
        var mobileRegex = new RegExp(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i, 'ig');

    ......
    .....
    .....

    router.get('/', function(req, res, next) {

      if (mobileRegex.test(req.headers['user-agent']) == true) {
          console.log('User-Agent: ' + req.headers['user-agent']);
        res.render('index-mobile')
      } else {
        res.render('index');
      }
    });

    router.get('/([\*])', function(req,res, next) { //Escaping * because cloudflare page rules aren't built right
      res.redirect('/')
    });

etc...
我假设“失败”是指移动设备没有被检测到


浏览器嗅探并不是特别可靠。你可以尝试使用类似的东西,但你必须让它保持最新。Mozilla自己只是简单地测试用户代理字符串的“Mobi”,因此您可能会看到这样做的失败率更低。

正确。我说的失败是指它加载了错误的页面。为什么正则表达式不可靠?不管发生什么,用户代理都是相同的。对我来说,这意味着这是我做事方式的一个js问题,不是吗?不是,我的意思是regex可能离可靠地检测所有移动设备还有很长的路要走。因为有数以万计的不同的设备在那里,他们中的大多数都在通过他们的牙齿说谎关于他们实际上是什么。如果您的意思是检测在同一个设备上间歇性失败,那么我会对控制台输出非常感兴趣……”这是因为g(全局)标志。RegExp构造函数也是额外的,literal就足够了。mobileRegex记住(在lastIndex属性中)最后一个匹配的索引,下一个测试(或exec)从那里开始-Reddit上的shvaikalesh