发起 GET 请求的示例:
import kbfetch from 'kbfetch'
kbfetch.get('https://api.example.com/data', { id: 1 })
// OR
kbfetch.g('https://api.example.com/data', { params: { id: 1 } })
发起 POST 请求的示例:
kbfetch.post('https://api.example.com/data', { id: 1 })
// OR需要query参数
kbfetch.post('https://api.example.com/data', { id: 1 }, { params: { qa: 1 } })
// OR
kbfetch.p('https://api.example.com/data', { params: { qa: 1 }, body: { id: 1 } })
path参数
kbfetch.get('https://baidu.com/:a/:b', { a: 1, b: 2 }).then(console.log)
kbfetch.post('https://baidu.com/:a/:b', { k: 2 }, { params: { a: 1, b: 2 } }).then(console.log)
kbfetch.p('https://api.example.com/:a/:b', { params: { a: 1, b: 2 }, body: { id: 1 } })
发起 其他method 请求的示例:
// e.g. 1
kbfetch.p('https://baidu.com', { method: 'PUT' })
// e.g. 2
kbfetch.g('https://baidu.com', { method: 'PATCH' })
取消请求示例:
timeout!=-1时,canAbort可以不设置
const ft = kbfetch.post('https://api.example.com/data', { id: 1 }, { canAbort: true })
ft.abort()
or
const ft = kbfetch.g('https://api.example.com/data', { params: { id: 1 }, timeout: 0 })
ft.abort()
设置公共参数比如token
kbfetch.baseHeaders = { token: 'XXX' }
kbfetch.baseParams = { access_token: 'xxx' }
kbfetch.baseBody = { access_token: 'xxx' }
get: (url: string, params?: Record<string, any>, init?: KbFetchInit)
g: (url: string, init?: KbFetchInit & { params?: Record<string, any> })
post: (url: string, body?: Record<string, any>, init?: KbFetchInit)
p: (url: string, init?: KbFetchInit)
uploadFile: (url: string, file: File, init?: KbFetchInit)
其他method可以通过p方法或者g方法,实现
KbFetchInit
类型扩展了标准的 RequestInit
,添加了一些可选的便捷属性:
-
baseUrl
- API地址的公共前缀 -
baseHeaders
- 公共的header,如token -
baseParams
- 公共的params,如企业微信的access_token,没有放在header里面,可以在这里设置 -
baseBody
- 公共body -
timeout
- 请求超时时间(毫秒) -
before
- 修改/记录请求参数的回调函数 -
parser
- 在返回resolve前解析响应的回调函数 -
after
- 响应结果的回调函数
import kbfetch, { createKbFetch, kbfc } from 'kbfetch'
// kbfc等同于kbfetch
// 请求单独配置
kbfetch.post(url, data, kbFetchInit)
kbfetch.get(url, params, kbFetchInit)
// 创建自定义实例
const ft = createKbFetch(KbFetchInit)
// ft.get ft.post
fetch SSE 实现示例:
import kbfetch from 'kbfetch'
const sse = (name: string, params: { ondata: (data: string) => any } & Record<string, any>) => {
const { ondata, ..._p } = params
return kbfetch.post(name, _p, {
timeout: 0,
parser: rb => {
if (!rb.body) return
const reader = rb.body.getReader()
const push = () => {
// done 为数据流是否接收完成,boolean
// value 为返回数据,Uint8Array
return reader.read().then(({ done, value }) => {
if (done) return
ondata(new TextDecoder().decode(value))
// 持续读取流信息
return push()
})
}
// 开始读取流信息
return push()
},
after: v => v
})
}
在这个示例中,我们自定义了 before
和 after
函数,以修改请求初始化对象和响应结果。
更多关于 kbfetchInit
对象的详细信息,请参考原始的 TypeScript 定义文件。