AnObtain
简单又好用的HTTP库
安装
npm install an-obtain
or
yarn add an-obtain
快速上手
import obtain from 'an-obtain'
GET:
obtain.get(
'/api/user',
{
data: {id: '123456'},
headers: {sessionId: '123456'
}
).then(res => {
console.log('返回结果', res)
})
POST:
obtain.post(
'/api/sendUser',
{ data: [{name: 'jack', age: '24'}] },
{
headers: {sessionId: '123456'
}
).then(res => {
console.log('返回结果', res)
})
PUT:
obtain.put(
'/api/addUser',
{ data: [{name: 'jack', age: '24'}] },
{
headers: {sessionId: '123456'
}
).then(res => {
console.log('返回结果', res)
})
DELETE:
obtain.delete(
'/api/deleteUser/123456',
{
data: { name: 'jack' }
headers: {sessionId: '123456'
}
).then(res => {
console.log('返回结果', res)
})
REQUEST:
obtain.request(
{
url: '/api/sendUser',
method: 'get' | 'post' | 'put' | 'delete' | 'options' | 'head' | 'patch',
data: { users: [{name: 'jack', age: '24'}] }
headers: {sessionId: '123456'
}
).then(res => {
console.log('返回结果', res)
})
API
get
发送GET请求
obtain.get(url: 请求路径, config: 配置信息(具体详见下方 config 详细说明))
post
发送POST请求
obtain.post(url: 请求路径, data: 请求数据, config: 配置信息(具体详见下方 config 详细说明))
put
发送PUT请求
obtain.put(url: 请求路径, data: 请求数据, config: 配置信息(具体详见下方 config 详细说明))
delete
发送DELETE请求
obtain.delete(url: 请求路径, config: 配置信息(具体详见下方 config 详细说明))
options
发送OPTIONS请求
obtain.options(url: 请求路径, config: 配置信息(具体详见下方 config 详细说明))
head
发送HEAD请求
obtain.head(url: 请求路径, config: 配置信息(具体详见下方 config 详细说明))
patch
发送PATCH请求
obtain.put(url: 请求路径, data: 请求数据, config: 配置信息(具体详见下方 config 详细说明))
request
发送任意请求
obtain.request(config: 配置信息(具体详见下方 config 详细说明))
config
配置默认参数,比如默认请求前缀,超时时间等
obtain.config(config: 配置信息(具体详见下方 config 详细说明))
useInterceptor
请求拦截器
pre
添加请求拦截器
obtain.useInterceptor.pre(
function fulfilled(config) {
...在请求之前做些什么
return config;
},
function rejected(error) {
...这里处理请求错误
return Promise.reject(error)
}
)
rear
添加响应拦截器
obtain.useInterceptor.rear(
function fulfilled(result) {
...在响应之后做些什么
return result;
},
function rejected(error) {
...这里处理响应错误
return Promise.reject(error)
}
)
可链式调用 obtain.pre(...).rear(...)
cancelToken
创建一个可取消请求的实例对象,将对象放入任意请求的 config.cancelToken 中,可通过 cancel 取消该请求
const cancelToken = obtain.cancelToken()
obtain.get('/api/user', { headers: { sessionId: '123456' }, cancelToken: cancelToken })
// 取消请求
cancelToken.cancel(message: 取消请求的原因(可选))
取消请求后,请求的promise会reject出一个CancelError对象
obtain.get(...).catch(e => { console.log(e) }) // => { message: 你的取消原因, __IS_CANCEL__: true }
注意,在请求还未请求之前 或者 未将该对象放入任何一个请求当中,直接调用 cancel 会抛出异常信息
createRef
创建一个请求的实例对象,可通过该实例对象单独为当前请求设置拦截器,以及会默认配置一个取消请求的对象,将此对象放入请求的 config.ref 中
const ref = obtain.createRef()
ref.useInterceptor.pre((config) => {
console.log('这是我的自定义前置拦截器', config)
return config
}).rear((res) => {
console.log('这是我的自定义后置拦截器', res)
return res
})
ref.disableGlobal() // 可以不使用全局的拦截器
obtain.get('/api/user', { headers: { sessionId: '123456' }, ref: ref })
// ref 中含有取消请求对象,可以取消该请求
ref.cancelToken.cancel(message: 取消请求的原因(可选))
useInterceptor
同obtain.useInterceptor
disableGlobal
调用此函数后 ref挂载的请求执行时将不会执行其他的拦截器
useCache
- 使用接口缓存,需要传入一个缓存ID,会根据缓存ID去匹配缓存池,可选传入一个时长,表示缓存时长,单位为秒,超过时长会删除缓存并重新请求,如果不传则永久存在直到用户手动清空或其他因素导致存储消失
- 如果命中,则直接返回命中的缓存数据,
- 如果没有命中,则会在请求成功后将数据放入缓存池中,并会生成一个缓存ID,返回给 useCache().next() 传入的函数入参中
- 再放入缓存之前,如果调用了when并传递了一个 函数,则会将返回传递给该函数,该函数需返回一个boolean值,如果为true则会进行缓存,并调用next传入的函数,如果为false 则不做任何事
缓存池:会在本地 indexDB 里面创建一个 Obtain_Cache_Pool 的数据库,其中创建一个 CachePool 表用于存放缓存数据,
操作indexDB,推荐本人的另一个库 an-db
ref.useCache(localStorage.getItem('cacheId'), 60000).when(({ data }) => data.code === '0000').next(cacheId => localStorage.setItem('cacheId', cacheId))
// 使用localStorage里的cacheId 作为缓存ID,并要求只缓存一分钟,并且要求接口返回的code为 '0000' 时才缓存,请求成功且满足缓存条件后会调用next传递的函数并将缓存ID作为入参进行传递,如果你给我的缓存ID为undefined或null,则会生成一个新的uuid作为缓存ID进行传递
useThrottle
接口节流,对于相同URL,相同请求,相同请求头的请求如果同时发起两个,那么只会发起第一个请求,后续的请求都不会发起请求会等待第一个的请求结果。
ref.useThrottle()
cancelToken
同obtain.cancelToken
delCache
删除缓存,传入一个缓存ID,返回promise
obtain.delCache(localStorage.getItem('cacheId'))
config 详解
{
// `url` 是用于请求的服务器 URL
url: '/user',
// `method` 是创建请求时使用的方法
method: 'get', // default
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',
// `headers` 是即将被发送的自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `data` 是作为请求主体被发送的数据,当method === 'get' 时,会进行格式化参数加在url后面,像这样 '/api/user?firstName=Fred'
data: {
firstName: 'Fred'
},
// `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
// 如果请求话费了超过 `timeout` 的时间,请求将被中断
timeout: 1000,
// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default
// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress: function (progressEvent) {
// 对原生进度事件的处理
},
// `maxContentLength` 定义允许的响应内容的最大尺寸
maxContentLength: 2000,
// `cancelToken` 指定用于取消请求的 cancel token
// (查看后面的 Cancellation 这节了解更多)
cancelToken: obtain.cancelToken()
// `ref` 指定当前请求的实例对象,可用于设置自定义的拦截器,默认含有取消对象
ref: obtain.createRef()
}
响应结构
某个请求的响应包含以下信息
{
// `data` 由服务器提供的响应
data: {},
// `status` 来自服务器响应的 HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: 'OK',
// `headers` 服务器响应的头
headers: {},
// `config` 是为请求提供的配置信息
config: {},
// 请求对象信息
request: {}
}