热门搜索 :
考研考公
您的当前位置:首页正文

JS HTTP请求终极解决方案 - fly.js

来源:东饰资讯网

简介

  1. 提供统一的 Promise API。
  2. 支持浏览器环境,轻量且非常轻量
  3. 支持 Node 环境。
  4. 支持请求/响应拦截器。
  5. 自动转换 JSON 数据。
  6. 支持切换底层 Http Engine,可轻松适配各种运行环境
  7. 浏览器端支持全局Ajax拦截 。
  8. H5页面内嵌到原生 APP 中时,支持将 http 请求转发到 Native。支持直接请求图片
  9. 高度可定制、可拆卸、可拼装。

定位与目标

与axios和Fetch对比

安装

使用NPM

npm install flyio

使用CDN

<script 

UMD


例子

下面示例如无特殊说明,则在浏览器和node环境下都能执行。

发起GET请求

var fly=require("flyio")
//通过用户id获取信息,参数直接写在url中
fly.get('/user?id=133')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

//query参数通过对象传递
fly.get('/user', {
      id: 133
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

发起POST请求

fly.post('/user', {
    name: 'Doris',
    age: 24
    phone:"18513222525"
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

发起多个并发请求

function getUserRecords() {
  return fly.get('/user/133/records');
}

function getUserProjects() {
  return fly.get('/user/133/projects');
}

fly.all([getUserRecords(), getUserProjects()])
  .then(fly.spread(function (records, projects) {
    //两个请求都完成
  }))
  .catch(function(error){
    console.log(error)
  })

直接通过 request 接口发起请求

//直接调用request函数发起post请求
fly.request("/test",{hh:5},{
    method:"post",
    timeout:5000 //超时设置为5s
 })
.then(d=>{ console.log("request result:",d)})
.catch((e) => console.log("error", e))

发送URLSearchParams

const params = new URLSearchParams();
params.append('a', 1);
fly.post("",params)
.then(d=>{ console.log("request result:",d)})

注:Node环境不存在URLSearchParams。各个浏览器对URLSearchParams的支持程度也不同,使用时务必注意

发送 FormData

 var formData = new FormData();
 var log=console.log
 formData.append('username', 'Chris');
 fly.post("../package.json",formData).then(log).catch(log)

请求二进制数据

fly.get("/Fly/v.png",null,{
    responseType:"arraybuffer"
}).then(d=>{
  //d.data 为ArrayBuffer实例
})

注:在浏览器中时 responseType 值可为 "arraybuffer" 或"blob"之一。在node下只需设为 "stream"即可。

拦截器

Fly支持请求/响应拦截器,可以通过它在请求发起之前和收到响应数据之后做一些预处理。


//添加请求拦截器
fly.interceptors.request.use((config,promise)=>{
    //给所有请求添加自定义header
    config.headers["X-Tag"]="flyio";
    //可以通过promise.reject/resolve直接中止请求
    //promise.resolve("fake data")
    return config;
})

//添加响应拦截器,响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
    (response,promise) => {
        //只将请求结果的data字段返回
        return response.data
    },
    (err,promise) => {
        //发生网络错误后会走到这里
        //promise.resolve("ssss")
    }
)

如果你想移除拦截器,只需要将拦截器设为null即可:

fly.interceptors.request.use(null)
fly.interceptors.response.use(null,null)

Node

错误处理

请求失败之后,catch 捕获到的 err 为 Error 的一个实例,err有两个字段:

{
  message:"Not Find 404", //错误消息
  status:404 //如果服务器可通,则为http请求状态码。网络异常时为0,网络超时为1
}
错误码 含义
0 网络错误
1 请求超时
2 文件下载成功,但保存失败,此错误只出现node环境下
>=200 http请求状态码

请求配置选项

可配置选项:

{
  headers:{}, //http请求头,
  baseURL:"", //请求基地址
  timeout:0,//超时时间,为0时则无超时限制
  withCredentials:false //跨域时是否发送cookie
}

配置支持实例级配置单次请求配置

实例级配置

实例级配置可用于当前Fly实例发起的所有请求

//定义公共headers
fly.config.headers={xx:5,bb:6,dd:7}
//设置超时
fly.config.timeout=10000;
//设置请求基地址
fly.config.baseURL="https://wendux.github.io/"

单次请求配置

需要对单次请求配置时,需使用request方法,配置只对当次请求有效。

fly.request("/test",{hh:5},{
    method:"post",
    timeout:5000 //超时设置为5s
})

注:若单次配置和实例配置冲突,则会优先使用单次请求配置

API

fly.get(url, data, options)

发起 get 请求,url请求地址,data为请求数据,在浏览器环境下类型可以是:

String|Json|Object|Array|Blob|ArrayBuffer|FormData

options为请求配置项。

fly.post(url, data, options)

发起post请求,参数含义同fly.get。

fly.request(url, data, options)

发起请求,参数含义同上,在使用此API时需要指定options 的method:

//GET请求
fly.request("/user/8" null, {method:"get"})
//DELETE 请求
fly.request("/user/8/delete", null, {method:"delete"})
//PUT请求
fly.request("/user/register", {name:"doris"}, {method:"PUT"})
......

fly.all([])

发起多个并发请求,参数是一个promise 数组;当所有请求都成功后才会调用then,只要有一个失败,就会调catch

创建Fly实例

为方便使用,在引入flyio库之后,会创建一个默认实例,一般情况下大多数请求都是通过默认实例发出的,但在一些场景中需要多个实例(可能使用不同的配置请求),这时你可以手动new一个:

//npm、node环境下
var  Fly=require("flyio/dist/npm/fly") //注意!此时引入的是 "fio/dist/npm/fly"
var nFly=new Fly();

//CDN引入时直接new
var nFly=new Fly();

Http Engine

全局Ajax拦截

在浏览器中,可以通过用 Fly engine 替换 XMLHttpRequest 的方式拦截全局的的 Ajax 请求,无论上层使用的是何种网络库。

体积

在浏览器环境下,一个库的大小是非常重要的。这方面 Fly 做的很好,它在保持强大的功能的同时,将自己的身材控制到了最好。min 只有 4.6K 左右,GZIP 压缩后不到 2K,体积是 axios 的四分之一。

Finally

补充一句

招前端,招前端,招前端!最近有找工作或者想换工作的私信我哦。 职位地点:北京

Top