SuperAgent 是 Node.js 與瀏覽器端廣泛使用的 HTTP 請求庫,提供鏈式 API、Promise 支援、自動序列化、重試機制等現代化功能。
npm install superagent
// CommonJS
const request = require('superagent');
// ES Module
import request from 'superagent';
所有方法皆回傳 SuperAgentRequest 實例,支援鏈式呼叫:
request
.get('/api/users')
.query({ page: 1, limit: 20 }) // 查詢字串
.set('Authorization', 'Bearer token')
.then(res => console.log(res.body))
.catch(err => console.error(err));
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));
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}`);
});
});
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;
}
}
status、response 屬性。.ok(res => res.status < 500) 自訂「成功」條件,避免 4xx 拋出錯誤。SuperAgent 內建型別定義,搭配泛型可獲得完整型別推論:
interface User { id: number; name: string; }
const res = await request.get('/api/users/1');
console.log(res.body.name); // 型別安全