mpvue框架使用flyio请求

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/weixin_43992330/article/details/89317938

1.npm安装

npm install flyio --save.

2.src下新建utils/request.js文件

import Fly from 'flyio/dist/npm/wx'
const fly = new Fly()
const host = 'https://rmall.ukelink.net'
// 添加请求拦截器
fly.interceptors.request.use((request) => {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  console.log(request)
  // request.headers["X-Tag"] = "flyio";
  // request.headers['content-type']= 'application/json';
  request.headers = {
    'X-Tag': 'flyio',
    'content-type': 'application/json'
  }
 
  let authParams = {
    // 公共参数
    'categoryType': 'SaleGoodsType@sim',
    'streamNo': 'wxapp153570682909641893',
    'reqSource': 'MALL_H5',
    'appid': 'string',
    'timestamp': new Date().getTime(),
    'sign': 'string'
  }
 
  request.body && Object.keys(request.body).forEach((val) => {
    if (request.body[val] === '') {
      delete request.body[val]
    };
  })
  request.body = {
    ...request.body,
    ...authParams
  }
  return request
})
 
// 添加响应拦截器
fly.interceptors.response.use(
  (response) => {
    wx.hideLoading()
    return response.data // 请求成功之后将返回值返回
  },
  (err) => {
    // 请求出错,根据返回状态码判断出错原因
    console.log(err)
    wx.hideLoading()
    if (err) {
      return '请求失败'
    };
  }
)
 
fly.config.baseURL = host
 
export default fly

3.main中引用到原型

import fly from './utils/request'
Vue.prototype.$fly = fly

4.使用

this.$fly.request({
      method: 'post', // post/get 请求方式
      url: '/mms/country/queryValidZoneListForMallHome',
      body: {}
    }).then(res => {
      console.log(res)
    })

关于请求拦截

比方说我们每次请求我们自己的服务器接口的时候需要带上appID,用户登陆后需要带上openId


// 请求拦截
fly.interceptors.request.use((request)=>{
 
  request.body.appId = 'xxx'
    // 用户的openId在获取之后添加到全局变量中如果存在,我们将它添加到请求参数里面
  let openId = Vue.prototype.globalData.openId;
  if(openId){
    request.body.openId = openId
  }
})

当服务器发生错误,或者用户网络错误导致请求失败的时候,我们可以添加一个响应拦截

// 响应拦截
fly.interceptors.response.use(
  (response) => {
 
 
  },
  (err) => {
    //发生网络错误后会走到这里
    //return Promise.resolve("ssss")
    wx.hideLoading();
    wx.showToast({
      title:'网络不流畅,请稍后再试!',
      icon:'none',
    });
 
  })

猜你喜欢

转载自blog.csdn.net/weixin_43992330/article/details/89317938