http-fetch-client
TypeScript icon, indicating that this package has built-in type declarations

2.0.14 • Public • Published

http-fetch-client.js

npm version npm download codecov

浏览器端 fetch client 类, 和一般的fetch不一样哦

其他语言的README: 简体中文, English

安装

npm install --save http-fetch-client

用法

发送一个GET请求

import FetchClient from 'http-fetch-client';

let fetch = new FetchClient();
fetch.request(
  '/test',
  {
    method: 'GET',
    body: {}
  }
)

以中间件方式实现回调

import FetchClient from 'http-fetch-client';

let fetch = new FetchClient();
fetch.request(...).use(({ response }) => {
  if (response.ok) {
    //  response.status in 200 - 300
  } else {
    //
  }
})

添加全局中间件,处理事物

创建后每次调用request/get/post/del/pull请求都会进入

PS: 注意,这里是fetch.use 而非 fetch.request(...).use

import FetchClient from 'http-fetch-client';

let fetch = new FetchClient();
fetch.use(({ response }) => {
  if (response.ok) {
    //  response.status in 200 - 300
  } else {
    //
  }
})

支持 async & promise 的中间件~

  • 使用promise

PS: 需要手动调用next 才能继续执行剩下的中间件

import FetchClient from 'http-fetch-client';

let fetch = new FetchClient();
fetch.request(...).use(({ response, request }, next) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('first after 1000ms');
      resolve(next());
    }, 1000);
  })
}).use(({ response }) => {
  console.log('second')
})
// console
// first after 1000ms
// second;
  • 使用async
import FetchClient from 'http-fetch-client';

let fetch = new FetchClient();
fetch.request(...).use(async ({ response, request }, next) => {
  return await setTimeout(() => {
    console.log('first after 1000ms');
    next();
  }, 1000);
}).use(({ response }) => {
  console.log('second')
})
// console
// first after 1000ms
// second;

通过 async 实现 中间件级联

import FetchClient from 'http-fetch-client';

let fetch = new FetchClient();
fetch.use(async function ({ response, request }, next) {
  console.log('global start');
  await next();
  console.log('global end');
});
fetch.request(...).use(async function ({ response, request }, next) {
  console.log('request start');
  await next();
  console.log('request end');
});
// console
// global start
// request start
// request end
// global end

停止后续的中间件执行

返回 Promise 或者 使用 async function 不执行 next

import FetchClient from 'http-fetch-client';

let fetch = new FetchClient();
fetch.request(...).use(async function ({ response }) {
  console.log('first');
}).use(function ({ response }) {
  console.log('second');
});
// console
// first

其他周期的中间件支持 ( beforeSend/error/success )

  • beforeSend 发送前,只有全局中间件能起效
  • success 默认项 成功返回了结果 status !== 0
  • error status === 0 网络错误时候
import FetchClient from 'http-fetch-client';

let fetch = new FetchClient();
fetch.use({
  beforeSend: ({ request }) => {
    request.header.set('X-Custom-Header', 'some');
  },
  error: ({ response, request }) => {
    // ...
  },
  success: ({ response, request }) => {
    // ...
  }
}));

GET/POST/PUT/DEL RESTful 的请求方式

import FetchClient from 'http-fetch-client';

let fetch = new FetchClient();
fetch.get(url[, options])
fetch.post(url[, options])
fetch.put(url[, options])
fetch.del(url[, options])

等价于

fetch.request(url, { method: 'GET'||'POST'||'PUT'||'DELETE'})

Response

Method

  • text/json/blob 对返回的内容进行格式化
fetch.get(...).use(({ response }) => {
  console.log(response.getBody()) // 根据 response header 的 Content-Type 自动格式化
  console.log(response.text()) // String: test
  console.log(response.json()) // Object: {a:'..'}
})
  • getHeaders 返回response headers
  • isTimeout 返回是否超时
  • isAborted 返回是否取消

Attribute

  • status {Number} http状态
  • ok {Boolean} http状态在200-300中间

Request

import { Request } from 'http-fetch-client';
new Request(url, options);

Method

  • getHeaders 获取请求头
  • setHeaders 设置请求头
  • getBody/getBodyForm/getBodyJson/getBodyFormData 获取请求body, 并转化为某种格式
  • setBody 设置请求body
  • getUrl/getUrlWithQuery(for GET) 获取url
  • getOptions 获取 options
  • setOptions 设置 options
  • getMethod 获取 method

Options Attribute

  • sendType {String} 发送的数据格式,支持 json/form(default),设置会会自动添加header中的 Content-Type
{
  'json': 'application/json; charset=UTF-8', // default
  'form': 'application/x-www-form-urlencoded; charset=UTF-8'
}
  • acceptType {String} 接受的数据格式,支持 json(default),设置会会自动添加header中的 Accept
{
  'json': 'application/json,text/javascript' // default
}
  • async {Boolean}
  • body|data {Object}
  • headers {Object}

PS: no callback to onsuccess or onerror

例子

待丰富 https://github.com/ignous/http-fetch-client-examples

Package Sidebar

Install

npm i http-fetch-client

Weekly Downloads

39

Version

2.0.14

License

MIT

Unpacked Size

104 kB

Total Files

34

Last publish

Collaborators

  • ignous