@ourea/fetch
安装
$ npm install @ourea/fetch --save
使用
import Http, { HttpError } from '@ourea/fetch'
const http = Http(opt)
初始化配置
const options = {
config?: {
baseUrl: String,
timeout: Number,
credentials: String,
headers: Object<key|value>,
},
before?: (Function | Promise)[],
after?: (Function | Promise)[],
error?: Function | Promise,
wrapperFunc?: Function,
allow?: String[]
}
配置 | 说明 | 默认值 | 其它 |
---|
allow | client 允许的请求类型 | ['get', 'post', 'put', 'delete', 'upload', 'download'] | 可选 |
before | 前置钩子(钩子数组) | [] | 可选 |
after | 后置钩子(钩子数组) | [] | 可选 |
config | fetch配置项 | | 参考fetch api 文档 |
error | 全局错误处理函数 | null | 可选 |
方法
- get(url, [params], [options]) // 基于初始化配置的 allow
- post(url, [params], [options]) // 基于初始化配置的 allow
- put(url, [params], [options]) // 基于初始化配置的 allow
- delete(url, [params], [options]) // 基于初始化配置的 allow
- upload(url, [params], [options]) // 基于初始化配置的 allow
- download(url, [params], [options]) // 基于初始化配置的 allow
- setOption(option) 设置请求配置
- setErrorHook(func) 设置全局错误处理器
- injectBefore(func) 增加前置拦截器
- injectAfter(func) 增加后置拦截器
内置错误码
- HTTP_STATUS_ERROR - 服务器未正常响应
- REQUEST_TIMEOUT - 请求超时
- TOKEN_EXPIRE - token校验失败
- RESPONSE_PARSING_FAILED - response 解析出错
import Http, { HttpError } from '@ourea/fetch'
http.setErrorHook(async (httpError, fetchUrl) => {
if (httpError.code === HttpError.ERROR_CODE.HTTP_STATUS_ERROR) {
const { msg, error, error_description } = await httpError.response.json()
return new HttpError({
message: msg | error_description | error,
code: httpError.httpStatus,
httpStatus: httpError.httpStatus,
})
}
console.log('[HTTP ERROR]', fetchUrl, httpError)
})
前/后置钩子
前置钩子
- 前置钩子的参数为
{ url, opt }
,返回值也必须为{ url, opt }
或者无返回 - 如果需要走错误处理可以直接抛出错误
throw new Error('find error in before hook .')
示例
http.injectBefore(({ url, opt }) => {
const { headers, params } = opt
const token = 'XXXXXXXX'
const auth = 'xxxxxxxx'
headers['Authorization'] = `Basic ${auth}`
headers['Token'] = `${token}`
return { url, opt: { ...opt, headers }}
})
后置钩子
- 后置钩子只有在请求码为
200
的情况下才会执行,非200
的请求则直接跳转到errorHook
- 钩子的参数为
response
,若钩子函数返回的是HttpError
的实例的话,当前请求的promise会被reject,
这次请求的失败信息将也会触发onError事件 - 若某一个钩子返回了
HttpError
则后续的钩子则不会执行
http.injectAfter(rsp => {
try {
const { success, code, message, msg } = rsp
if (!success || code === 40101) {
if (code === 40101) {
return new HttpError({
code,
httpStatus: HttpError.ERROR_CODE.TOKEN_EXPIRE,
message: message || msg || HttpError.HTTP_ERROR_MAP[HttpError.ERROR_CODE.TOKEN_EXPIRE],
})
} else if (code !== 0) {
return new HttpError({
code,
httpStatus: CUSTOM_HTTP_ERROR_STATUS,
message: message || msg || '后台返回未知错误',
})
}
}
} catch (error) {
return new HttpError({
code: CUSTOM_HTTP_ERROR_STATUS,
httpStatus: HttpError.RESPONSE_PARSING_FAILED,
message: HttpError.HTTP_ERROR_MAP[HttpError.ERROR_CODE.RESPONSE_PARSING_FAILED],
})
}
})
例子
http.injectAfter(function(rsp){
return new vFetch.HttpError({
code: '001',
message: 'error test',
httpStatus: null,
})
})
HttpError
构造函数
HttpError
实例的构造函数为 http.HttpError
示例
...
throw new http.HttpError({
code: "TOKEN_EXPIRE"
httpStatus: 401
message: "用户认证失败"
})
...
整体示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="../dist/vFetch.js"></script>
</head>
<body>
<script>
console.log(window, VFetch.HttpError, VFetch.HTTP_ERROR_MAP, VFetch.httpConfig)
const http = VFetch(VFetch.httpConfig)
http.injectAfter(function(rst){
console.log('injectAfter', rst)
return new vFetch.HttpError({
code: '001',
message: 'error test',
httpStatus: null,
})
})
http.injectAfter(function(){
console.log(222);
})
http.setErrorHook(async function(e){
console.log(e, 'error');
const timeoutPromise = new Promise(resolve => setTimeout(() => {
resolve('async hook')
}, 1000))
const data = await timeoutPromise
console.log(data)
})
http.get('t.json', {a:2, c:3}, { baseUrl, headers, timeout, ... })
.then(rst => {
}).catch(e => {
})
</script>
</body>
</html>