fly.js是什么?
一个支持所有JavaScript运行环境的基于Promise的、支持请求转发、强大的http请求库。可以让您在多个端上尽可能大限度的实现代码复用(官网解释)
fly.js有什么特点:
- 提供统一的 Promise API。
- 浏览器环境下,轻量且非常轻量 。
- 支持多种JavaScript 运行环境
- 支持请求/响应拦截器。
- 自动转换 JSON 数据。
- 支持切换底层 Http Engine,可轻松适配各种运行环境。
- 浏览器端支持全局Ajax拦截 。
- H5页面内嵌到原生 APP 中时,支持将 http 请求转发到 Native。支持直接请求图片
定位与目标:
Fly 的定位是成为 Javascript http请求的终极解决方案。也就是说,在任何能够执行 Javascript 的环境,只要具有访问网络的能力,Fly都能运行在其上,提供统一的API。
使用方法:
1.结合npm
npm install flyio
2.使用CDN(浏览器中)
<script src="https://unpkg.com/flyio/dist/fly.min.js"></script>
3.UMD(浏览器中
https://unpkg.com/flyio/dist/umd/fly.umd.min.js
因为作者使用npm在mpvue微信小程序中用到,下面将经验详细与大家分享:
npm下载好组建后,我在微信小程序的src/main.js目录下引用了官网的这段代码:
var Fly=require("flyio/dist/npm/wx") var fly=new Fly
刚开始在后面加入了这段代码,
Vue.prototype.$http = fly // 将fly实例挂在vue原型上
但是在post传参时一直失败,最后不得不放弃。老老实实在每次使用是用上以下代码来请求数据:
发起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))
以上由于传递参数用上了 { } 花括号,这是传递JSON数据参数,很多时候我们只需要传递一个【type=type】就可以,
所以我们还可以用如下方式:
main.js
var Fly = require("flyio/dist/npm/wx") var fly = new Fly Vue.prototype.$http = fly // 将fly实例挂在vue原型上
index.vue
var newest = String(this.$mp.query.type); this.$http .post( "https://tashimall.miniprogram.weixin-api-test.yokead.com/bulletin/getBulletin.json", "type=" + newest ) .then(res => { //输出请求数据 this.allBulletin = res.data.data; }) .catch(err => { console.log(err.status, err.message); });
注意⚠️:红色标出部分