微信小程序request(ajax)接口请求封装

最近在进行小程序的编写,需要调用后端接口,经常要用到wx.request方法,所以就自己封装了一下,简化一下代码

1、app.js  创建全局数据

App({
  // 全局数据
  globalUrl:{
    url:"http://localhost:8081/demo/" 
 }
})

 

2、方法封装(新建文件夹util,工具文件,在文件夹下创建utils.js文件,用于对方法封装;请求地址提取出来使用app.js中的url)

utils.js

// 全局request封装
/**
* config:{
*  url:'',
*  method:'',
*  data:""
* }
*/

/**
 * 请求方式可传,不传为GET
 * postData:参数,json类型
 * callback:成功的回调函数
 * errorCallBack:失败的回调函数
 */

const APP = getApp();
//项目URL相同部分,减轻代码量,同时方便项目迁移
const REQUESTURL =  APP.globalUrl.url;
function request(config, callback, errorCallBack) {
    //请求接口时默认loading效果,黑色本框转圈圈
    wx.showLoading();
    wx.request({
      url: REQUESTURL+config.url,
      method:config.method?config.method:"GET",
      data:config.data?config.data:"",
      success(res){
        if(res.data.code==200){
          wx.hideLoading();             //隐藏loading
          //默认成功展示对号
          if (callback) {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
            callback(res)
          }
        }else if(res.data.code==406){
        //跳转登录
        }else{
          wx.hideLoading();           //隐藏loading
          if (errorCallBack) {
            errorCallBack(res)
          } else {
             wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      }
    })
}
module.exports = {
  request: request
}          

 

3、请求封装函数的引用,page里面创建一个文件夹index,创建四种文件,在js里面加入:

/**
*引入getApp();是app.js中的全局数据URL
*utils引入使用请求封装函数
*/
const APP = getApp();
var utils = require("../util/utils.js");
Page({
  /**
   * 页面的初始数据
   */
  data: { },
  onLoad: function (options) {
    var that = this;
    var getVinUrl = "/survey/getVin/";
   //ajax请求 utils.request({ url: getVinUrl, method:
'GET', data: this.data.phone }, function (res) { //请求成功 connsole.log(res); }, function (err) { //请求失败 connsole.log(err); }); } })

 

 

原文地址:https://www.cnblogs.com/liubingyjui/p/12322130.html