@ichaingo/request
v1.5.37
Published
This library was generated with [Nx](https://nx.dev).
Readme
request
This library was generated with Nx.
一个基于 Axios 的 HTTP 请求库,提供了统一的请求拦截器和响应处理。
功能特性
- 基于 Axios 的 HTTP 客户端
- 自动添加通用请求头
- 统一的错误处理
- 支持返回完整响应对象(包含 headers 信息)
使用方法
基本用法
import axiosInstance from '@ichaingo/request';
// 普通请求,返回 response.data
const data = await axiosInstance.get('/api/users');
console.log(data); // 直接是响应数据获取完整响应对象
当你需要访问响应头信息时,可以使用 returnFullResponse 选项:
import axiosInstance from '@ichaingo/request';
import { ApiRequestConfig } from '@ichaingo/request/types';
const config: ApiRequestConfig = {
returnFullResponse: true // 返回完整的 response 对象
};
const response = await axiosInstance.get('/api/users', config);
// 现在可以访问完整的响应信息
console.log('状态码:', response.status);
console.log('响应头:', response.headers);
console.log('响应数据:', response.data);
// 读取特定的 header 信息
const contentType = response.headers['content-type'];
const customHeader = response.headers['x-custom-header'];POST 请求示例
const config: ApiRequestConfig = {
returnFullResponse: true,
headers: {
'Content-Type': 'application/json'
}
};
const response = await axiosInstance.post('/api/users', {
name: 'John Doe',
email: '[email protected]'
}, config);
if (response.status === 201) {
console.log('用户创建成功');
console.log('Location header:', response.headers['location']);
}API 配置选项
ApiRequestConfig
继承自 Axios 的 AxiosRequestConfig,并添加了以下选项:
withCredentials?: boolean- 是否包含凭据returnFullResponse?: boolean- 是否返回完整的响应对象(默认为 false)
当 returnFullResponse 为 true 时,请求将返回完整的 Axios 响应对象,包含:
data- 响应数据status- HTTP 状态码statusText- HTTP 状态文本headers- 响应头信息config- 请求配置
Building
Run nx build request to build the library.
Running unit tests
Run nx test request to execute the unit tests via Vitest.
更多示例
查看 example.ts 文件获取更多使用示例。
