温馨提示×

Ubuntu Nodejs如何集成第三方服务

小樊
49
2026-01-12 04:01:58
栏目: 编程语言

在 Ubuntu 上,Node.js 集成第三方服务通常分为两类:一是作为客户端调用外部 HTTP/HTTPS API,二是作为服务端被反向代理或对接消息/监控等外部系统。下面给出可直接落地的做法与关键注意事项。


调用外部 HTTP API 的常用方式

  • 使用 axios(推荐):基于 Promise,支持拦截器、超时、取消等,适合生产环境。示例:
    • 安装:npm install axios
    • 调用:
      const axios = require('axios');
      
      // GET
      axios.get('https://api.example.com/data', {
        headers: { 'Authorization': 'Bearer <TOKEN>' },
        timeout: 5000
      }).then(r => console.log(r.data)).catch(e => {
        if (e.response) console.error('HTTP', e.response.status, e.response.data);
        else if (e.request) console.error('No response');
        else console.error('Error', e.message);
      });
      
      // POST
      axios.post('https://api.example.com/data', { key: 'value' }, {
        headers: { 'Content-Type': 'application/json' }
      }).then(r => console.log(r.data));
      
  • 使用 内置 http/https:无需依赖,适合轻量或底层控制。
    const https = require('https');
    
    https.get('https://api.example.com/data', { headers: { 'Authorization': 'Bearer <TOKEN>' } }, res => {
      let d = '';
      res.on('data', c => d += c);
      res.on('end', () => console.log(JSON.parse(d)));
    }).on('error', e => console.error(e));
    
  • 使用 fetch(Node.js 17+ 内置;低版本可用 node-fetch):
    // Node >= 17
    fetch('https://api.example.com/data', {
      headers: { 'Authorization': 'Bearer <TOKEN>' }
    }).then(r => r.json()).then(console.log).catch(console.error);
    
  • 健壮性与安全要点:
    • 统一处理网络错误、非 2xx 状态码与超时;
    • API Key/Secret 放入环境变量(如 process.env.API_KEY),不要硬编码;
    • 需要重试/限流/并发控制时,引入 axios-retryp-limit 等库。

将 Node.js 接入 Apache2 或 Nginx 反向代理

  • 使用 Apache2 mod_proxy(适合已有 Apache 的场景)
    • 启用模块:sudo a2enmod proxy proxy_http proxy_html headers
    • 虚拟主机示例(将域名请求代理到本地 3000 端口):
      <VirtualHost *:80>
        ServerName my-node-app.com
        ProxyPreserveHost On
        ProxyRequests Off
        ProxyPass / http://127.0.0.1:3000/
        ProxyPassReverse / http://127.0.0.1:3000/
        ErrorLog ${APACHE_LOG_DIR}/my-node-app_error.log
        CustomLog ${APACHE_LOG_DIR}/my-node-app_access.log combined
      </VirtualHost>
      
    • 启用站点并重启:sudo a2ensite my-node-app.conf && sudo systemctl restart apache2
  • 使用 Nginx(更轻量、高并发常用)
    • 站点配置示例(同时支持静态资源与 WebSocket):
      server {
        listen 80;
        server_name _;
        root /opt/yourapp/dist;
        index index.html;
      
        location / {
          try_files $uri $uri/ @proxy;
        }
      
        location @proxy {
          proxy_pass http://127.0.0.1:3000;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "Upgrade";
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_read_timeout 86400;
        }
      
        location ~ /\. { deny all; }
      }
      
    • 部署建议:静态资源由 Nginx 直出,动态接口走代理;WebSocket 需开启 HTTP/1.1Upgrade 头。

进程守护与运行监控

  • 使用 PM2 管理 Node.js 进程(开机自启、日志轮转、集群模式)
    • 安装:npm install -g pm2
    • 启动:pm2 start server.js --name myapp
    • 常用:pm2 logs myapppm2 restart myapppm2 listpm2 startup(生成 systemd 启动脚本)
  • 暴露 /metricsPrometheus 抓取(配合 Grafana 可视化)
    • 安装客户端:npm install prom-client
    • 示例:
      const client = require('prom-client');
      const http = require('http');
      
      const httpReqDur = new client.Histogram({
        name: 'http_request_duration_ms',
        help: 'Duration of HTTP requests in ms',
        labelNames: ['method', 'route', 'code'],
        buckets: [0.1, 5, 15, 50, 100, 200, 300, 400, 500]
      });
      
      const server = http.createServer((req, res) => {
        const end = httpReqDur.startTimer();
        res.on('finish', () => {
          end({ method: req.method, route: req.url, code: res.statusCode });
        });
        // ...你的业务处理
      });
      
      server.listen(3000, () => console.log('Metrics on :3000/metrics'));
      
    • 在 Prometheus 中抓取 http://<your-host>:3000/metrics,Grafana 配置 Prometheus 数据源并导入面板。

错误追踪与日志集成

  • 使用 Sentry 做错误监控与告警
    • 安装:npm install @sentry/node
    • 初始化(在应用入口,如 app.js):
      const Sentry = require('@sentry/node');
      Sentry.init({ dsn: process.env.SENTRY_DSN, environment: 'production' });
      
      // 示例:触发一个测试异常
      app.get('/', () => { throw new Error('Test Sentry error'); });
      
    • SENTRY_DSN 放入环境变量,便于不同环境切换。
  • 结构化日志(便于检索与聚合)
    • 使用 winston
      const { createLogger, format, transports } = require('winston');
      
      const logger = createLogger({
        level: 'info',
        format: format.combine(format.timestamp(), format.json()),
        transports: [
          new transports.File({ filename: 'error.log', level: 'error' }),
          new transports.File({ filename: 'combined.log' })
        ]
      });
      
      if (process.env.NODE_ENV !== 'production') {
        logger.add(new transports.Console({ format: format.simple() }));
      }
      
      logger.info('Hello, world!');
      logger.error('Something went wrong!');
      
    • 建议:生产环境输出 JSON 日志,配合 filebeat/logstash 送入 Elasticsearch/Loki

0