mpvue微信小程序http请求终极解决方案-fly.js

fly.js是什么?

  一个支持所有JavaScript运行环境的基于Promise的、支持请求转发、强大的http请求库。可以让您在多个端上尽可能大限度的实现代码复用(官网解释)

fly.js有什么特点:

  1. 提供统一的 Promise API。
  2. 浏览器环境下,轻量且非常轻量 。
  3. 支持多种JavaScript 运行环境
  4. 支持请求/响应拦截器。
  5. 自动转换 JSON 数据。
  6. 支持切换底层 Http Engine,可轻松适配各种运行环境。
  7. 浏览器端支持全局Ajax拦截 。
  8. 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); });

 

注意⚠️:红色标出部分

 

转载于:https://www.cnblogs.com/Webzhoushifa/p/9557274.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值