← 中文资源

简体中文版本

Superagent 类型化 HTTP 响应解析

用 Superagent 完成 GET 与 POST:自动解析响应体、声明式重试条件、双重超时控制,以及 JSON 与表单两种提交类型。

阅读英文原文

示例说明

Superagent 把 HTTP 细节表达为可链式配置的请求构造器:query 追加查询参数、set 管理头、type 切换提交格式。retry 的回调函数让重试条件完全可编程——只有网络错误或 5xx 才重试,4xx 业务错误直接返回。timeout 的 response 与 deadline 两级时限分别防单次等待与总耗时失控。

技术要点

  • agent 复用 Cookie 语义保持会话
  • retry 回调精确圈定可重试错误
  • response 与 deadline 双时限防挂死

代码解读

GET 示例链式设置授权头与字段裁剪参数,profile.body 已是解析好的对象;retry(2, fn) 表示最多重试两次且仅当谓词为真。POST 示例分别演示 JSON 与表单编码提交,send 传入的对象会按 type 序列化,error 事件处理器兜底记录提交失败。

使用建议

超时值要与上游服务 P99 耗时对齐再留余量。agent 实例会保留 Cookie,跨租户场景注意状态隔离。需要拦截器式统一处理时可用它的插件机制扩展请求对象。

代码示例

import superagent from 'superagent';

const agent = superagent.agent();

const profile = await agent
  .get('https://api.example.com/profile')
  .set('Authorization', 'Bearer demo-token')
  .query({ fields: 'name,email' })
  .timeout({ response: 4000, deadline: 9000 })
  .retry(2, (err, res) => !!err || res.status >= 500);

console.log('profile name:', profile.body.name);

const created = await agent
  .post('https://api.example.com/orders')
  .type('json')
  .send({ sku: 'A-1', quantity: 3 })
  .on('error', (err) => console.error('submit failed:', err.message));

console.log('created order id:', created.body.id);

const form = await agent
  .post('https://api.example.com/feedback')
  .type('form')
  .send({ rating: 5, comment: 'great' });
console.log('form status:', form.status);