1.1.7 • Published 7 years ago

tfetch v1.1.7

Weekly downloads
38
License
ISC
Repository
-
Last release
7 years ago

tFetch

安装

npm install tfetch

使用

import tFetch from 'tfetch'

const http = new tFetch(opt)

配置

配置说明默认值其它
before后置钩子(钩子数组)可选
after前置钩子(钩子数组)可选
baseUrl请求地址前缀'/'
timeout超时1000
errorCodeKey错误代码字段名可选,启用token失效拦截时使用
tokenExpireCodetoken校验失败时的errorcode可选,启用token失效拦截时使用
reponseFormaterresponse stream 处理方法jsonarrayBuffer\blob\formData\json\text
conffetch配置项参考fetch api 文档
errorHandler全局错误处理函数可选

方法

内置error code

  • HTTP_STATUS_ERROR - 服务器未正常响应
  • REQUEST_TIMEOUT - 请求超时
  • TOKEN_EXPIRE - token校验失败
  • RESPONSE_PARSING_FAILED - reponse 解析出错

injectAfter function

如果injectAfter function有返回值且返回值是HttpError的实例的话,当前请求的promise会被reject, 这次请求的失败信息将也会触发onError事件。

!!! 注意,inject function接受的参数是一个reponse实例。 如需触发onError事件,因为response对象的解析方法均为异步,所以inject function必须返回一个promise

例子

http.injectAfter(async function(response){
  const rsp = await response.json()
  // do some response check

  return new tFetch.HttpError({
    code: '001',
    message: 'error test',
    httpStatus: null,
  })
})

Content-Type

为了方便使用,下面这几种情况下tFetch会根据content-type去自动设置request body的类型, 处理body对象的构建

  • application/x-www-form-urlencoded (默认) 如果传入的params是object类型,则自动构建请求body
  • multipart/form-data 自动根据请求的parmas object 构建 FromData对象
  • application/json 如果传入的params是object类型,则自动转换成JsonString,如果为string类型,则直接用传入的params

请求的params为FormData类型时,request的body不会进行自动转换

httpError

构造函数

httpError实例的构造函数为 tFetch.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/tFetch.js"></script>
</head>
<body>
  <script>
    const http = new tFetch({
      baseUrl: './',
      errorCodeKey: 'errorCode',
      tokenExpireCode: '101-003'
    })

    http.get('t.json', {a:2, c:3}, {timeout: 100})
      .then(rst => {
        console.log(rst, 'success');
      }).catch(e => {
        console.log(e, 'error');
      })
  </script> 
</body>
</html>
1.1.7

7 years ago

1.1.6

7 years ago

1.1.5

7 years ago

1.1.4

7 years ago

1.1.3

7 years ago

1.1.2

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.22

7 years ago

1.0.21

7 years ago

1.0.20

7 years ago

1.0.19

7 years ago

1.0.18

7 years ago

1.0.17

7 years ago

1.0.16

7 years ago

1.0.15

8 years ago

1.0.14

8 years ago

1.0.13

8 years ago

1.0.12

8 years ago

1.0.11

8 years ago

1.0.10

8 years ago

1.0.9

8 years ago

1.0.8

8 years ago

1.0.7

8 years ago

1.0.6

8 years ago

1.0.4

8 years ago

1.0.3

8 years ago

1.0.2

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago