介绍
ag-request 是一个基于 axios 封装的 npm 包,提供了一些常用的网络请求方法,如:get、post、put、delete 调用,支持多个拦截器选择,并提供了默认参数配置,是一个优秀的前端请求工具。
安装
在你的项目中使用 npm 包管理器安装 ag-request:
npm install ag-request --save
快速开始
发送请求
发送一个简单的 GET 请求:
import { get } from 'ag-request'; get('https://jsonplaceholder.typicode.com/posts/1') .then(res => console.log(res)) .catch(err => console.error(err));
发送一个包含参数的 GET 请求:
import { get } from 'ag-request'; get('https://jsonplaceholder.typicode.com/posts', { id: 1 }) .then(res => console.log(res)) .catch(err => console.error(err));
发送一个 POST 请求:
import { post } from 'ag-request'; post('https://jsonplaceholder.typicode.com/posts', { title: 'hello', body: 'world' }) .then(res => console.log(res)) .catch(err => console.error(err));
自定义默认配置
以下是一个定制化的例子,你可以使用 create
方法创建一个新的实例并进行配置:
-- -------------------- ---- ------- ------ - ------ - ---- ------------- ----- --- - -------- -------- ---------------------------------------- -------- ------ -------- - ------------------ -------- - --- ------------------- --------- -- ----------------- ---------- -- --------------------展开代码
API 文档
请求方法
以下是可用的请求方法:
get(url[, params[, config]])
delete(url[, config]])
head(url[, config]])
options(url[, config]])
post(url[, data[, config]])
put(url[, data[, config]])
patch(url[, data[, config]])
其中,参数分别为:
url
指定请求的 URL。params
指定请求参数。data
指定请求体内容。config
指定请求配置,如:headers、timeout、paramsSerializer 等。
配置方法
以下是可用的配置方法:
create([config])
创建一个新的实例并进行配置。mergeConfig(config1, config2)
将两个请求配置对象合并。
以下是可配置的请求配置项:
baseURL
在路径之前添加的自定义的基础 URL。timeout
指定请求超时的毫秒数。headers
自定义的请求头。params
指定请求参数,用于 get 或 jsonp 请求。withCredentials
表示跨域请求时是否需要使用凭证。responseType
指定响应的数据格式。xsrfCookieName
指定 xsrf token 的 cookie 名称。xsrfHeaderName
指定 xsrf token 的 header 名称。validateStatus
定义需要解析为 resolve 的 HTTP 响应状态码范围。paramsSerializer
指定在请求之前对params
序列化的函数。
拦截器
以下是可用的拦截器方法:
use(onFulfilled, onRejected)
添加请求拦截器。eject(id)
删除请求拦截器。useResponse(onFulfilled, onRejected)
添加响应拦截器。ejectResponse(id)
删除响应拦截器。
以下是拦截器示例:
-- -------------------- ---- ------- ----- -------- - --------- ------------------- -- - ---------------------------- - ----------- ------ ------- --- ------------------------ -- - -- ----------- --- ---- - ----------------- - ------ ---- ---展开代码
总结
ag-request 是一个非常实用的前端请求工具,它提供了一些常用的网络请求方法,支持多个拦截器选择,并提供了默认参数配置,极大地提高了我们开发的效率,是一个非常优秀的 npm 包。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/5eedbeecb5cbfe1ea0611bac