2.1.6 • Published 11 months ago

@bytedo/fetch v2.1.6

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

ajax的全新封装

统一走fetch的风格。内置参数处理, 支持多实例。

浏览器兼容性

ChromeFirefoxSafariOperaEdgeIE
Latest ✔Latest ✔Latest ✔Latest ✔Latest ✔10+ ✔

版本

共有2个版本, 一个传统版本, 基于XMLHttpRequest; 另一个是新一代版本, 基于window.fetch()

注意:

由于window.fetch()只支持http/https协议, 所以在一些特殊的环境下(如electron等), 请使用传统版。

2个版本的区别

  1. 超时的返回值不一样。fetch版没有额外处理, 全由原生返回; 传统版为处理过, 统一返回Response对象

  2. 缓存参数不一致, 传统版只有传入no-store才不会缓存,其他任何值都会缓存, 缓存机制由headers及浏览器机制决定。 fetch版支持完整的参数, 详见原生fetch文档。

  3. 验证机制,传参不一样。传统版credentials为布尔值; fetch版本则是支持omit, same-origin, include。

示例

import fetch from '//dist.bytedo.org/fetch/dist/index.js'   // 传统版
// import fetch from '//dist.bytedo.org/fetch/dist/next.js'  // fetch版


fetch('/get_list', {body: {page: 1}})
  .then(r => r.json())
  .then(list => {
    console.log(list)
  })


// 创建一个新的fetch实例, 可传入新的基础域名, 和公共参数等
var f1 = fetch.create('//192.168.1.101', {headers: {token: 123456}})

f1('/get_list', {body: {page: 1}})
  .then(r => r.json())
  .then(list => {
    console.log(list)
  })

APIs

1. fetch(url, options)

发起一个网络请求, options的参数如下。 同时支持配置公共域名, 公共参数。

  • method<String> 默认GET, 可选GET/POST/PUT/DELETE...
  • body<Any> 要发送的数据, 如果是不允许有body的方式, 会被自动拼接到url上
  • cache<String> 是否缓存,
  • credentials<String/Boolean> 是否校验
  • signal<Object> 网络控制信号, 可用于中断请求
  • timeout<Number> 超时时间, 默认30秒, 单位毫秒
fetch.BASE_URL = '//192.168.1.100'
// 1.2.0开始支持注入
fetch.inject.request(function(conf) {
  // 无需返回值, 但需要注意这是引用类型,不要对带个conf赋值
  conf.headers.token = 123456
})

// 响应注入, 需要有返回值
fetch.inject.response(function(res) {
  return res.json()
})

2. fetch.create()

创建一个新的fetch实例, 可以无限创建多个实例(用于同一个项目中有多组不同的接口)。

var another = fetch.create()
another.BASE_URL = '//192.168.1.101'
// 新创建的实例, 也支持注入
another.inject.request(function(conf) {
  conf.headers.token = 123456
})

another.inject.response(function(res) {
  return res.json()
})

旧版本

请查阅 1.x

2.1.6

11 months ago

2.1.2

1 year ago

2.1.3

1 year ago

2.1.5

1 year ago

2.1.1

2 years ago

2.1.0

2 years ago

2.0.2

2 years ago

2.0.1

2 years ago

1.2.0

2 years ago

2.0.0

2 years ago

1.1.3

3 years ago

1.1.2

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago