如何在 nodejs 环境中处理用户代理?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22285921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:58:55  来源:igfitidea点击:

How to handle user-agent in nodejs environment?

node.jsexpressuser-agent

提问by Undefined Behavior

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?

我开始使用“ua-parser”包,但创建者太忙了,无法维护或提交...... npm ua-parser 已过时,需要直接从github下载。有人知道其他好的包,如 ua-parser 已更新并可与 expressjs 一起使用吗?或者有办法只用expressjs来处理?

回答by tpae

Have you looked at:

你看过:

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

参考:从内部 jade 获取用户代理

回答by John Williams

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.

一般有两种情况,你只需要简单的匹配,你不需要模块,你可以在 Node.js 中使用正则表达式。

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

另一个,如果你需要一个漂亮干净的浏览器类型输出,这对我来说效果最好。 https://www.npmjs.org/package/useragent

回答by decoder7283

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

我对 Express 的最佳解决方案...轻量级/快速! 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()
}