You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js API微服务中从GET请求获取浏览器的OS与架构信息

嗨,刚好之前做Node.js微服务时处理过类似的需求,来给你说说两种实用的方式,帮你从GET请求里拿到浏览器的操作系统和架构信息~

如何在Node.js API中获取浏览器的操作系统及架构信息

浏览器会在请求头的User-Agent字段里携带系统、架构、浏览器版本等信息,比如你提到的"Windows NT 10.0; Win64; x64"就是典型的Windows 64位系统的UA片段。下面是两种处理方式:

方法一:手动解析User-Agent字符串

如果不想引入额外依赖,可以自己写简单的正则匹配逻辑,针对常见系统做解析:

// 以Express框架为例
const express = require('express');
const app = express();

app.get('/api/system-info', (req, res) => {
  const userAgent = req.headers['user-agent'];
  if (!userAgent) {
    return res.status(400).json({ error: 'User-Agent header missing' });
  }

  let osInfo = 'Unknown OS';
  let archInfo = 'Unknown Architecture';

  // 匹配Windows系统及架构
  const windowsMatch = userAgent.match(/Windows NT (\d+\.\d+); (Win64; x64|Win32; x86)/);
  if (windowsMatch) {
    osInfo = `Windows ${windowsMatch[1]}`;
    archInfo = windowsMatch[2].split('; ')[1];
  }

  // 匹配macOS系统及架构
  const macMatch = userAgent.match(/Mac OS X (\d+_\d+_\d+)/);
  if (macMatch) {
    osInfo = `macOS ${macMatch[1].replace(/_/g, '.')}`;
    archInfo = userAgent.includes('arm64') || userAgent.includes('Apple Silicon') ? 'arm64' : 'x64';
  }

  // 匹配Linux系统及架构
  const linuxMatch = userAgent.match(/Linux (x86_64|i686|arm64|aarch64)/);
  if (linuxMatch) {
    osInfo = 'Linux';
    archInfo = linuxMatch[1];
  }

  res.json({
    originalUserAgent: userAgent,
    operatingSystem: osInfo,
    architecture: archInfo
  });
});

app.listen(3000, () => console.log('Server running on port 3000'));

方法二:使用现成的User-Agent解析库

如果需要覆盖更多边缘场景(比如小众系统、特殊浏览器),推荐用维护成熟的第三方库,比如ua-parser-js,它能帮你自动解析出结构化的系统、浏览器、架构信息:

// 先安装依赖
// npm install ua-parser-js

const express = require('express');
const { UAParser } = require('ua-parser-js');
const app = express();

app.get('/api/detailed-info', (req, res) => {
  const userAgent = req.headers['user-agent'];
  if (!userAgent) {
    return res.status(400).json({ error: 'User-Agent header not provided' });
  }

  const parser = new UAParser(userAgent);
  const parsedResult = parser.getResult();

  res.json({
    operatingSystem: `${parsedResult.os.name || 'Unknown'} ${parsedResult.os.version || ''}`.trim(),
    architecture: parsedResult.cpu.architecture || 'Unknown',
    browser: `${parsedResult.browser.name || 'Unknown'} ${parsedResult.browser.version || ''}`.trim()
  });
});

app.listen(3000, () => console.log('Server running on port 3000'));

小提醒:User-Agent字符串是可以被客户端伪造的,所以如果你的业务场景对系统信息的准确性要求极高,这种方式可能有局限,但绝大多数普通API场景下,这个方法足够可靠。

内容的提问来源于stack exchange,提问作者sulabh chaturvedi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:14:54