SuperAgent 使用指南:轻量级渐进式 HTTP 客户端库

SuperAgent 使用指南:轻量级渐进式 HTTP 客户端库

superagent Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs. superagent 项目地址: https://gitcode.com/gh_mirrors/sup/superagent

概述

SuperAgent 是一个轻量级、渐进式的 HTTP 客户端库,为浏览器和 Node.js 环境提供了简洁易用的 API。它具有以下特点:

  • 链式调用语法,代码可读性高
  • 支持 Promise 和 async/await
  • 自动处理 JSON 数据
  • 支持文件上传和表单提交
  • 提供请求重试机制
  • 支持 HTTP/2 协议

安装与基本使用

浏览器环境

<script src="superagent.js"></script>
<script>
  request
    .get('/api/data')
    .then(res => {
      console.log(res.body);
    });
</script>

Node.js 环境

const request = require('superagent');

request
  .post('/api/pet')
  .send({ name: 'Manny', species: 'cat' })
  .then(res => {
    console.log('成功:', res.body);
  });

核心功能详解

1. 发起请求

SuperAgent 支持所有 HTTP 方法:

// GET 请求
request.get('/search').then(...);

// POST 请求
request.post('/user').send({name: 'John'}).then(...);

// PUT 请求
request.put('/user/1').send({name: 'John'}).then(...);

// DELETE 请求
request.del('/user/1').then(...);

2. 请求头设置

request
  .get('/search')
  .set('API-Key', 'foobar')
  .set('Accept', 'application/json')
  .then(...);

或者一次性设置多个请求头:

request
  .get('/search')
  .set({
    'API-Key': 'foobar',
    'Accept': 'application/json'
  })
  .then(...);

3. 查询参数

对于 GET 请求,可以方便地添加查询参数:

request
  .get('/search')
  .query({ query: 'Manny' })
  .query({ range: '1..5' })
  .then(...);

或者:

request
  .get('/search')
  .query({ 
    query: 'Manny',
    range: '1..5'
  })
  .then(...);

4. 发送请求体

对于 POST/PUT 请求,可以发送各种格式的数据:

// 发送 JSON 数据
request
  .post('/user')
  .send({ name: 'John', age: 25 })
  .then(...);

// 发送表单数据
request
  .post('/user')
  .type('form')
  .send({ name: 'John' })
  .send({ age: '25' })
  .then(...);

// 发送 FormData 对象
const formData = new FormData();
formData.append('name', 'John');
request
  .post('/user')
  .send(formData)
  .then(...);

5. 文件上传

request
  .post('/upload')
  .attach('avatar', 'path/to/image.jpg', 'user.jpg')
  .field('name', 'John')
  .then(...);

6. 处理响应

响应对象包含丰富的信息:

request.get('/user/1').then(res => {
  // 响应状态
  console.log(res.status); // 200
  
  // 响应头
  console.log(res.headers['content-type']);
  
  // 响应体(自动解析的JSON)
  console.log(res.body.name);
  
  // 原始响应文本
  console.log(res.text);
});

7. 错误处理

request
  .get('/user/1')
  .then(res => {
    // 成功处理
  })
  .catch(err => {
    // 错误处理
    if (err.status === 404) {
      console.log('用户不存在');
    } else {
      console.log('服务器错误');
    }
  });

高级功能

1. 请求重试

request
  .get('https://example.com/api')
  .retry(3) // 最多重试3次
  .then(...);

2. 超时设置

request
  .get('/slow-api')
  .timeout({
    response: 5000,  // 等待5秒服务器开始响应
    deadline: 30000  // 但允许30秒完成整个请求
  })
  .then(...);

3. HTTP/2 支持

request
  .get('https://example.com/h2')
  .http2()
  .then(...);

4. 认证

// 基本认证
request.get('http://local').auth('user', 'pass').then(...);

// Bearer Token 认证
request.auth('my_token', { type: 'bearer' });

5. 代理和全局配置

// 创建代理实例
const agent = request.agent();

// 设置全局配置
agent
  .use(somePlugin)
  .auth('shared', 'credentials');

// 使用代理发起请求
agent.get('/with-auth').then(...);

实际应用示例

1. 用户登录

request
  .post('/api/login')
  .send({
    username: 'john',
    password: 'secret'
  })
  .then(res => {
    // 保存token
    localStorage.setItem('token', res.body.token);
  })
  .catch(err => {
    console.error('登录失败:', err.message);
  });

2. 分页获取数据

async function getUsers(page = 1, limit = 10) {
  try {
    const res = await request
      .get('/api/users')
      .query({ page, limit });
    
    return res.body;
  } catch (err) {
    console.error('获取用户失败:', err);
    return [];
  }
}

3. 文件上传带进度显示

const req = request
  .post('/api/upload')
  .attach('file', fileInput.files[0])
  .on('progress', event => {
    const percent = Math.round(event.percent);
    console.log(`上传进度: ${percent}%`);
  });

req.then(res => {
  console.log('上传成功:', res.body);
}).catch(err => {
  console.error('上传失败:', err);
});

最佳实践

  1. 错误处理:始终处理请求可能产生的错误
  2. 超时设置:为所有请求设置合理的超时时间
  3. 重试机制:对可能失败的请求实现重试逻辑
  4. 请求取消:在组件卸载等场景下取消未完成的请求
  5. 全局配置:使用代理(agent)共享通用配置
  6. 安全考虑:处理敏感数据时使用HTTPS和适当的认证方式

常见问题解决方案

1. 处理跨域请求

request
  .get('https://api.example.com/data')
  .withCredentials() // 发送凭据(cookie等)
  .then(...);

2. 处理大文件下载

const fs = require('fs');
const stream = fs.createWriteStream('large-file.zip');

request
  .get('https://example.com/large-file.zip')
  .pipe(stream);

3. 自定义序列化

// 自定义XML序列化
request.serialize['application/xml'] = function(obj) {
  return generateXML(obj);
};

request
  .post('/api/xml')
  .send({ data: 'value' })
  .type('xml')
  .then(...);

SuperAgent 以其简洁的 API 和强大的功能,成为处理 HTTP 请求的优秀选择。无论是简单的数据获取还是复杂的文件上传,它都能提供优雅的解决方案。

superagent Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs. superagent 项目地址: https://gitcode.com/gh_mirrors/sup/superagent

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阮曦薇Joe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值