萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Node.js SuperAgent 請求庫完整使用指南

SuperAgent 簡介

SuperAgent 是 Node.js 與瀏覽器端廣泛使用的 HTTP 請求庫,提供鏈式 API、Promise 支援、自動序列化、重試機制等現代化功能。

安裝與引入

npm install superagent
// CommonJS
const request = require('superagent');
// ES Module
import request from 'superagent';

核心 HTTP 方法

所有方法皆回傳 SuperAgentRequest 實例,支援鏈式呼叫:

GET 請求

request
  .get('/api/users')
  .query({ page: 1, limit: 20 })   // 查詢字串
  .set('Authorization', 'Bearer token')
  .then(res => console.log(res.body))
  .catch(err => console.error(err));

POST 請求

request
  .post('/api/users')
  .send({ name: 'John', email: 'john@example.com' }) // 自動設定 Content-Type: application/json
  .set('Accept', 'application/json')
  .then(res => console.log(res.body));

PUT / PATCH / DELETE

request.put('/api/users/1').send({ name: 'Jane' });
request.patch('/api/users/1').send({ email: 'jane@new.com' });
request.del('/api/users/1'); // del 是 delete 的別名

進階功能

檔案上傳

const fs = require('fs');
request
  .post('/api/upload')
  .attach('avatar', fs.createReadStream('photo.jpg'), 'photo.jpg')
  .field('userId', 123)
  .then(res => console.log(res.body));

自動重試與超時

request
  .get('/api/unstable')
  .retry(3)                    // 重試 3 次
  .timeout({ response: 5000 }) // 5 秒回應超時
  .then(res => ...);

攔截器與擴充

// 全域攔截器
request.use((req) => {
  req.set('X-Request-Id', uuid());
});

// 自定義插件
request.use((req) => {
  req.on('response', (res) => {
    console.log(`[${req.method}] ${req.url} → ${res.status}`);
  });
});

Promise / async-await 風格

async function fetchUser(id) {
  try {
    const res = await request.get(`/api/users/${id}`);
    return res.body;
  } catch (err) {
    if (err.status === 404) throw new Error('User not found');
    throw err;
  }
}

錯誤處理最佳實踐

  • 網路錯誤、超時、非 2xx 狀態碼皆會拋出錯誤,錯誤物件包含 status、response 屬性。
  • 使用 .ok(res => res.status < 500) 自訂「成功」條件,避免 4xx 拋出錯誤。
  • 生產環境建議統一錯誤處理中介層,記錄請求 ID、耗時、錯誤堆疊。

TypeScript 型別支援

SuperAgent 內建型別定義,搭配泛型可獲得完整型別推論:

interface User { id: number; name: string; }
const res = await request.get('/api/users/1');
console.log(res.body.name); // 型別安全
copyright © 萬盛學電腦網 all rights reserved