首页 > 热点 > 微信 > 正文

微信小程序中如何使用flyio封装网络请求

2024-07-22 01:18:05
字体:
来源:转载
供稿:网友

Flyio简介

Fly.js 通过在不同 JavaScript 运行时通过在底层切换不同的 Http Engine来实现多环境支持,但同时对用户层提供统一、标准的Promise API。不仅如此,Fly.js还支持请求/响应拦截器、自动转化JSON、请求转发等功能,详情请参考:https://github.com/wendux/fly 。

下面我们看看在微信小程序、mpvue中和中如何使用fly.

Flyio 官方地址

文档

github地址

Flyio的一些特点

fly.js 是一个基于 promise 的,轻量且强大的Javascript http 网络库,它有如下特点:

提供统一的 Promise API。 浏览器环境下,轻量且非常轻量 。 支持多种JavaScript 运行环境 支持请求/响应拦截器。 自动转换 JSON 数据。 支持切换底层 Http Engine,可轻松适配各种运行环境。 浏览器端支持全局Ajax拦截 。 H5页面内嵌到原生 APP 中时,支持将 http 请求转发到 Native。支持直接请求图片。

在小程序中使用flyio请求,封装代码如下

一、src下新建utils/request.js文件

var Fly=require("flyio/dist/npm/wx") import { getCache } from '../utils'const request = new Fly()// 全局加载提示 - 设定时间let ltime = 0;function closeLoading(param) {  ltime-- }request.interceptors.request.use((request) => {  // 全局加载提示 - 展示提示  // wx.showNavigationBarLoading()   ltime++  let dataSource = getCache("dataSource")  request.headers = {    "Content-Type": "application/x-www-form-urlencoded",    "source": "miniApp",    "dataSource": dataSource ? dataSource : ''  }  // 没用到  if (request.url.indexOf('getReviewInfo') != -1) {    closeLoading()    return request  }  // 登录  console.log('这是token');  console.log();  let type = '';  if(request.url.indexOf("wxLogin") != -1) {    type = request.body.loginType;  }  console.log(getCache("token"));  console.log('这是token');  if (request.url.indexOf("wxLogin") == -1 || type == 'WORKBENCH') {    // let storeId = getCache("storeId");    let storeCode = getCache("storeCode");    let inviter = getCache("inviter");    let token = getCache("token");    request.headers = {      "Content-Type": "application/x-www-form-urlencoded",      "source": "miniApp",      "token": token,      "storeCode": storeCode,      "inviter": inviter    }    console.log('打印request');    console.log(request);    console.log('打印request');    let dataSource = getCache("dataSource")    if (dataSource) {      request.headers['dataSource'] = dataSource    }  }  return request})request.interceptors.response.use((response, promise) => {     closeLoading()    // wx.hideNavigationBarLoading()    // 微信运维统计    if (response.status) {      wx.reportMonitor('0', +(response.status))    }    if (response.headers.date) {      let time = new Date().getTime() - new Date(response.headers.date).getTime()      wx.reportMonitor('1', +(time))    }    // 错误提示    if (response.status != 200) {      wx.showToast({        title: '出错啦!请稍后再试试哦~',        icon: 'none',        duration: 2000      })    }    return promise.resolve(response.data)  },  (err, promise) => {    wx.hideNavigationBarLoading()    return promise.resolve()  })export default request            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表