微信小程序-fly网络请求库

 为什么使用fly网络请求库

当我们在做微信小程序端的交互的时候,发现jquey、axios这些都无法在小程序中使用,因为小程序中js的运行环境与普通浏览器的运行环境不同,页面的脚本逻辑是在JsCore中运行的,而JsCore中没有xmlhttpRequest对象,所以无法使用它们,同时JsCore无法提供window对象,这也是我们在小程序中无法使用window对象的原因,在这时候我们的主角fly大显身手???

fly是一种可以在微信小程序运行的交互方式,提供统一的 Promise API,轻量且非常轻量,支持请求/响应拦截器,小程序用法:

首先,先使用  npm install flyio,安装fly;

后面在小程序中引入:

var Fly=require("flyio/dist/npm/wx") 

var fly=new Fly

1.get请求

fly.get('/user?id=133')

  .then(function (response) {

    console.log(response);

  })

  .catch(function (error) {

    console.log(error);

  });

 

2.post请求

fly.post('/user', {

    name: 'Doris',

    age: 24

    phone:"18513222525"

  })

  .then(function (response) {

    console.log(response);

  })

  .catch(function (error) {

    console.log(error);

  });

 

3.拦截器

支持两种。一种是请求拦截器,在请求之前做一些预处理;一种是响应拦截器,在响应获取数据之后做一些处理。

 

请求拦截器:

fly.interceptors.request.use((request)={

    //给所有请求添加自定义header

    request.headers["X-Tag"]="flyio";

  //打印出请求体

  console.log(request.body)  

    //可以显式返回request, 也可以不返回,没有返回值时拦截器中默认返回request

    return request;

})

响应拦截器:

//添加响应拦截器,响应拦截器会在then/catch处理之前执行

fly.interceptors.response.use(

    (response) = {

        //只将请求结果的data字段返回

        return response.data

    },

    (err) = {

        //发生网络错误后会走到这里

        //return Promise.resolve("ssss")

    }

)

使用示例:

下载wx.js源码:https://github.com/wendux/fly/tree/master/dist/npm/wx.js

const app = getApp()
var Fly = require("./wx.js") //wx.js为您下载的源码文件
var fly = new Fly();
//添加拦截器
fly.interceptors.request.use((config, promise) => {
  //给所有请求添加自定义header
  if(false){
    config.headers["X-Tag"] = "flyio";
    return config;
  } 
});
//配置请求基地址
// fly.config.baseURL = 'http://gank.io/api/data/%E7%A6%8F%E5%88%A9'
Page({
  data: {

  },
  postFly() {
    var data = {};
    data.stage_id=1;
    data.page=1;
    data.limit=2;
    fly.post('http://www.qubaobei.com/ios/cf/dish_list.php', data)
      .then(function(response) {
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });
  },
  testFly() {
    //发起get请求
    fly.get("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&page=1&limit=2", {

    }).then((d) => {
      //输出请求数据
      console.log(d.data)
      //输出响应头
      console.log(d.header)
    }).catch(err => {
      console.log(err.status, err.message)
    })

  },
  onLoad: function() {
    // this.testFly();
  },
})

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值