fly.js是什么?javascript
一个支持全部JavaScript运行环境的基于Promise的、支持请求转发、强大的http请求库。可让您在多个端上尽量大限度的实现代码复用(官网解释)vue
fly.js有什么特色:java
定位与目标:shell
Fly 的定位是成为 Javascript http请求的终极解决方案。也就是说,在任何可以执行 Javascript 的环境,只要具备访问网络的能力,Fly都能运行在其上,提供统一的API。npm
使用方法: json
1.结合npm小程序
npm install flyio
2.使用CDN(浏览器中)微信小程序
<script src="https://unpkg.com/flyio/dist/fly.min.js"></script>
3.UMD(浏览器中api
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); });
注意⚠️:红色标出部分