SuperAgent 使用指南:轻量级渐进式 HTTP 客户端库
概述
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);
});
最佳实践
- 错误处理:始终处理请求可能产生的错误
- 超时设置:为所有请求设置合理的超时时间
- 重试机制:对可能失败的请求实现重试逻辑
- 请求取消:在组件卸载等场景下取消未完成的请求
- 全局配置:使用代理(agent)共享通用配置
- 安全考虑:处理敏感数据时使用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 请求的优秀选择。无论是简单的数据获取还是复杂的文件上传,它都能提供优雅的解决方案。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考