http

默认请求实例

http 是 Oiyo 数据获取模块提供的默认请求实例,无前置配置,可直接发起请求。

oiyo 已将该 http 默认导入,无需再 import 即可直接使用。

http.create()

基于当前实例派生新实例,与 createHttp 派生出的实例共用同一套方法

声明

http.create(config: HttpConfig): Http

参数

config 的属性以及类型继承于 HttpCommonOptions

属性类型默认值说明
onRequestfunction-发起请求前的钩子
onRequestErrorfunction-请求发起失败的钩子
onResponsefunction-收到响应后的钩子
onResponseErrorfunction-响应非 2xx 的钩子

钩子

config.onRequest()

钩子触发时机:发起请求前

  • 声明
    interface HttpConfig {
      onRequest(context: { resource: HttpURL, options: HttpOptions }): MaybePromise<void>>
    }
    
  • 示例
    const api = createHttp({
      onRequest({ resource, options }) {
        console.log('向该资源发起请求:', resource)
      },
    })
    

config.onRequestError()

触发时机:请求发起失败

  • 声明
    interface HttpConfig {
      onRequestError(context: { resource: HttpURL, options: HttpOptions, error: Error }): MaybePromise<void>>
    }
    
  • 示例
    const api = createHttp({
      onRequestError({ resource, options, error }) {
        console.error('请求失败', error)
      },
    })
    

config.onResponse()

触发时机:收到响应后

  • 声明
    interface HttpConfig {
      onResponse(context: { resource: HttpURL, options: HttpOptions, response: HttpRawResponse }): MaybePromise<void>>
    }
    
  • 示例
    const api = createHttp({
      onRequestError({ resource, options, response }) {
        console.log('收到响应', response.statusCode, response.data)
      },
    })
    

config.onResponseError()

触发时机:响应非 2xx 的钩子

  • 声明
    interface HttpConfig {
      onResponseError(context: { resource: HttpURL, options: HttpOptions, response: HttpRawResponse }): MaybePromise<void>>
    }
    
  • 示例
    const api = createHttp({
      onResponseError({ response }) {
        console.error('响应错误', response.statusCode)
      },
    })
    
钩子可声明在任意一层配置(实例、派生实例、单次请求)上。多层配置的同名钩子会在配置合并阶段串联为一个函数,按层级顺序依次执行。

http.request()

普通请求方法

声明

http.request(options: HttpRequestOptions): Http

参数

options 的属性以及类型继承于 HttpCommonOptions

属性类型默认值说明
onChunkfunction-流式数据监听

http.upload()

文件上传

声明

http.upload(options: HttpUploadOptions): Http

参数

options 的属性以及类型继承于 HttpCommonOptions

属性类型默认值说明
namestring-用于给服务端识别的名称
methodPOSTPOST请求方法
onProgressfunction-上传进度监听

http.download()

文件下载

声明

http.download(options: HttpDownloadOptions): Http

参数

options 的属性以及类型继承于 HttpCommonOptions

属性类型默认值说明
methodGETGET请求方法
onProgressfunction-下载进度监听

行为

  • baseURL,资源必须传绝对地址,相对地址会因缺省基础地址而报错。
  • 无预置钩子与公共 headers,每次请求只走单次配置。
  • createHttp 派生出的实例共用同一套配置项、钩子、重试与中断能力。
如需 baseURL、公共 headers、拦截 hooks 等团队约定,请使用 createHttp 创建实例。

相关

使用手册:前往了解 http 使用方法