微信小程序axios封装和mock调试

前言

刚开始学习微信小程序,微信小程序通过自带的wx.request发送https请求(文档地址),写法感觉类似之前的jQuery,当嵌套多了以后看起来很不直观。

由于之前对React + Ant Design Pro框架比较熟悉,所以才用promise函数对小程序的wx.request进行了封装,结合antd的mock进行调试。


axios封装

在微信小程序中新建如下文件:

  • utils/request.js:使用promise封装微信小程序的wx.request方法
  • services/service.js:存放API方法
  • pages/index/index.jsindex.wxmlindex.jsindex.wxss:小程序页面4个文件

utils/request.js:只是进行了简单的封装,failtoken等因素暂时未考虑。

 // 使用promise封装wx.request
const request = params => {
    
    
   return new Promise((resolve, reject) => {
    
    
     wx.request({
    
    
       ...params,
       success: result => {
    
    
         resolve(result);
       },
       fail: err => {
    
    
         reject(err);
       }
     })
   })
 }

 // 二次封装生成axios
 const axios = {
    
    
   get: url => {
    
    
     return request({
    
    
       url,
       method: 'GET'
     })
   },
   post: (url, params) => {
    
    
     return request({
    
    
       url,
       data: params,
       method: 'POST'
     })
   }
 }

 export {
    
    
   axios
 }

service/service.js:存放了4个常用的案例,GET请求不带参数、GET请求带参数、POST请求不带参数和POST请求带参数。注意api地址和端口和后续mock服务器一致。

import {
    
    
  axios
} from '../utils/request';

// axios.get测试,不带参数
export async function getPlayerList() {
    
    
  return axios.get(`http://localhost:8000/api/get/playerList`).then(response => response.data);
}

// axios.get测试,带参数
export async function getPlayerInfoByName(name) {
    
    
  return axios.get(`http://localhost:8000/api/get/playerInfo/by/name/${
      
      name}`).then(response => response.data);
}


// axios.post测试,不带参数
export async function getClubList() {
    
    
  return axios.post(`http://localhost:8000/api/get/clubList`).then(response => response.data);
}

// axios.post测试,带参数
export async function getClubListWithParams(params) {
    
    
  return axios.post(`http://localhost:8000/api/get/clubInfo/by/name`, params).then(response => response.data);
}

页面index.js:把后端获取的数据打印出来

import {
    
    
  getPlayerList,
  getPlayerInfoByName,
  getClubList,
  getClubListWithParams
} from '../../services/service';

Page({
    
    
  data: {
    
    
    swiperList: []
  },

  onLoad: function () {
    
    
    // get请求(不带参数)
    getPlayerList().then(data => {
    
    
      console.log('GET请求不带参数:');
      console.log(data);
    });

    // get请求(带参数)
    const name = 'Ronaldo';
    getPlayerInfoByName(name).then(data => {
    
    
      console.log('GET请求带参数:');
      console.log(data);
    });

    // post请求不带参数
    getClubList().then(data => {
    
    
      console.log('POST请求不带参数:');
      console.log(data);
    });

    // post请求带参数
    const params = {
    
    
      name: 'madrid'
    }
    getClubListWithParams(params).then(data => {
    
    
      console.log('POST请求带参数:');
      console.log(data);
    });
  },
})

mock调试

小程序可以使用mockjs作为后端数据模拟源,由于小程序文件只有2M容量,为了不让小程序代码看起来太臃肿,所以我把mock数据放在ant design promock文件夹下,使用的时候只要启动 ant design pro框架即可。

ant design pro自带mockjs,启动后为了模拟真实情况带了1个delayTime为2000ms。

weixin.js

import {
    
     delay } from 'roadhog-api-doc';
import delayTime from '../delayTime';

const weixin = {
    
    
  /**
   * 微信小程序get请求测试,不带参数
   */
  'GET /api/get/playerList': (req, res) => {
    
    
    const r = [
      {
    
    
        name: 'Ronaldo',
        age3: 35,
      },
      {
    
    
        name: 'Buffon',
        age: 43,
      },
    ];
    res.status(200).send(r);
  },

  /**
   * 微信小程序get请求测试,带参数
   */
  'GET /api/get/playerInfo/by/name/:name': (req, res) => {
    
    
    const {
    
     name } = req.params;
    let r = {
    
    };
    if (name === 'Ronaldo') {
    
    
      r = {
    
    
        name: 'Ronaldo',
        age: 34,
        club: 'Juventus',
      };
    }

    res.status(200).send(r);
  },

  /**
   * 微信小程序post请求测试,不带参数
   */
  'POST /api/get/clubList': (req, res) => {
    
    
    const r = [
      {
    
    
        name: 'Real Madrid',
        champions: 13,
      },
      {
    
    
        name: 'Barcelona',
        champions: 5,
      },
    ];
    res.status(200).send(r);
  },

  /**
   * 微信小程序post请求测试,带参数
   */
  'POST /api/get/clubInfo/by/name': (req, res) => {
    
    
    const {
    
     name } = req.body;
    let r = {
    
    };

    if (name === 'madrid') {
    
    
      r = {
    
    
        name: 'Real Madrid',
        champions: 13,
      };
    } else {
    
    
      r = {
    
    
        name: 'Barcelona',
        champions: 5,
      };
    }
    res.status(200).send(r);
  },
};

export default delay(weixin, delayTime);

启动ant design pro后可以看到mock数据通过localhost:8000端口可以获取
在这里插入图片描述


效果:

微信小程序启动后,效果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34307801/article/details/112131685
今日推荐