SuperAgent 使用指南:轻量级 AJAX 请求库详解
概述
SuperAgent 是一款轻量级、渐进式的 AJAX API 库,专为灵活性、可读性和低学习曲线而设计。它既可以在浏览器环境中使用,也支持 Node.js 环境。本文将全面介绍 SuperAgent 的核心功能和使用方法。
基本请求
发起请求
SuperAgent 提供了简洁的链式调用 API 来发起 HTTP 请求:
request
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.then(res => {
console.log('响应数据:', res.body);
});
请求方法
支持所有常见的 HTTP 方法:
// GET 请求
request.get('/search').then(res => {});
// POST 请求
request.post('/user').send({name: 'John'}).then(res => {});
// PUT 请求
request.put('/user/1').send({name: 'John'}).then(res => {});
// DELETE 请求
request.del('/user/1').then(res => {});
// HEAD 请求
request.head('/user').then(res => {});
请求配置
设置请求头
request
.get('/search')
.set('API-Key', 'foobar')
.set('Accept', 'application/json')
.then(res => {});
也可以一次设置多个请求头:
request
.get('/search')
.set({ 'API-Key': 'foobar', Accept: 'application/json' })
.then(res => {});
内容类型设置
// 设置 JSON 内容类型
request.post('/user').type('json').send({name: 'John'});
// 设置表单内容类型
request.post('/user').type('form').send({name: 'John'});
// 设置 XML 内容类型
request.post('/user').type('xml').send('<name>John</name>');
请求数据
发送 JSON 数据
request
.post('/user')
.send({ name: 'John', age: 30 })
.then(res => {});
发送表单数据
request
.post('/user')
.type('form')
.send({ name: 'John' })
.send({ age: '30' })
.then(res => {});
发送查询参数
// GET 请求带查询参数
request
.get('/search')
.query({ query: 'Manny', range: '1..5', order: 'desc' })
.then(res => {});
// 也可以分开设置
request
.get('/search')
.query({ query: 'Manny' })
.query({ range: '1..5' })
.then(res => {});
响应处理
响应数据
SuperAgent 会自动解析常见的响应类型:
request.get('/user').then(res => {
console.log(res.body); // 解析后的响应体
console.log(res.text); // 原始响应文本
console.log(res.header); // 响应头
console.log(res.status); // 状态码
});
响应状态检查
request.get('/user').then(res => {
if (res.ok) {
console.log('请求成功');
} else if (res.clientError) {
console.log('客户端错误');
} else if (res.serverError) {
console.log('服务器错误');
}
});
高级功能
重试机制
request
.get('https://example.com/search')
.retry(2) // 最多重试2次
.then(res => {})
.catch(err => {});
超时设置
// 设置整个请求的超时时间
request.get('/search').timeout(5000).then(res => {});
// 设置响应超时时间
request.get('/search').timeout({response: 2000}).then(res => {});
HTTP/2 支持
const res = await request
.get('https://example.com/h2')
.http2();
TLS 配置
const key = fs.readFileSync('key.pem');
const cert = fs.readFileSync('cert.pem');
request
.post('/client-auth')
.key(key)
.cert(cert)
.then(res => {});
错误处理
request
.get('/search')
.then(res => {
// 成功处理
})
.catch(err => {
// 错误处理
console.error(err.message);
if (err.response) {
console.error(err.response.body);
}
});
浏览器特定功能
二进制响应
request.get('/binary.data')
.responseType('blob')
.then(res => {
// res.body 将是 Blob 类型
});
FormData 支持
request.post('/user')
.send(new FormData(document.getElementById('myForm')))
.then(res => {});
总结
SuperAgent 提供了简洁而强大的 API 来处理 HTTP 请求,无论是简单的 GET 请求还是复杂的多部分表单上传,都能轻松应对。它的链式调用设计使得代码更加清晰易读,自动化的请求和响应处理减少了开发者的工作量。
通过本文的介绍,你应该已经掌握了 SuperAgent 的核心功能,可以开始在项目中应用它来简化你的 HTTP 请求处理逻辑了。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考