0.0.27 • Published 4 months ago

kbfetch v0.0.27

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

使用示例

发起 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 }
    // 其他kbFetchInit属性
})

发起 POST 请求的示例:

kbfetch.post('https://api.example.com/data', { id: 1 })

取消请求示例: timeout!=-1时,canAbort可以不设置

const ft = kbfetch.post('https://api.example.com/data', { id: 1 }, { canAbort: true })
ft.abort()
const ft = kbfetch.g('https://api.example.com/data', { params: { id: 1 }, timeout: 0 })
ft.abort()

自定义选项

KbFetchInit 类型扩展了标准的 RequestInit,添加了一些可选的便捷属性:

  • baseUrl - API的基础网址
  • timeout - 请求超时时间(毫秒)
  • before - 修改/记录请求参数的回调函数
  • parser - 在返回resolve前解析响应的回调函数
  • after - 响应结果的回调函数
import kbfetch, { createKbFetch } from '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
    })
}

在这个示例中,我们自定义了 beforeafter 函数,以修改请求初始化对象和响应结果。

更多关于 kbfetchInit 对象的详细信息,请参考原始的 TypeScript 定义文件。

0.0.26

4 months ago

0.0.27

4 months ago

0.0.20

6 months ago

0.0.21

6 months ago

0.0.22

6 months ago

0.0.11

6 months ago

0.0.12

6 months ago

0.0.13

6 months ago

0.0.14

6 months ago

0.0.15

6 months ago

0.0.16

6 months ago

0.0.17

6 months ago

0.0.18

6 months ago

0.0.19

6 months ago

0.0.8

7 months ago

0.0.7

7 months ago

0.0.6

7 months ago

0.0.5

7 months ago

0.0.4

7 months ago

0.0.3

7 months ago

0.0.2

7 months ago