How to handle user-agent in nodejs environment?

感情迁移 提交于 2019-12-09 05:01:03

问题


I start to using the package "ua-parser" but the creator is too busy to mantain or commit... the npm ua-parser is outdate, and need to download directly from github. Someone know about other good package like ua-parser that is updated and can be used with expressjs? Or have a way to handle just with expressjs?


回答1:


Have you looked at:

  • https://github.com/biggora/express-useragent

Or, write your own middleware:

app.use(function(req, res, next) {
  res.locals.ua = req.get('User-Agent');
  next();
});

Reference: get user agent from inside jade




回答2:


There are two general situations, where you just need simple matching, and you don't need a module for this, you can just use regex in Node.

var isIpad = !!req.headers['user-agent'].match(/iPad/);
var isAndroid = !!req.headers['user-agent'].match(/Android/);

==> true, false

The other, if you need a nice clean output of browser type, this worked best for me. https://www.npmjs.org/package/useragent




回答3:


My optimal solution for Express...lightweight/fast! https://www.npmjs.com/package/express-useragent

  app.use(require('express-useragent').express())

Your middleware...

app.use(function(req, res, next) {
  req.session.useragent = {
     browser: req.useragent.browser,
     version: req.useragent.version,
     os: req.useragent.os,
     platform: req.useragent.platform
  }
  console.log(JSON.stringify(req.session.useragent, null ,4))
  next()
}


来源:https://stackoverflow.com/questions/22285921/how-to-handle-user-agent-in-nodejs-environment

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