微信小程序 wx.request 请求封装

本文详细比较了在微信小程序中使用三种封装wx.request的方法,包括模块化封装、统一api接口和直接使用wx.request。通过实例展示了如何在实际开发中应用这些技巧,帮助开发者提升代码复用性和可维护性。
摘要由CSDN通过智能技术生成

方式1:

// utils/wxAjax.js
const baseUrl = 'https://*****/';//这里可通过环境变量获取不同域名
// 封装请求
module.exports = function (options) {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: baseUrl + options.url,
      method:
        options.method === 'GET' ? options.data : JSON.stringify(options.data),
      data: options.data,
      header: {
        'content-type': 'application/json',
        // 'x-token': 'x-token'
      },
      success: function (res) {
        resolve(res);
        //这里可以加状态判断
      },
      fail: function (error) {
        reject(error);
      },
      complete: () => {
        setTimeout(() => {
          wx.hideLoading();
        }, 100);
      },
    });
  });
};

使用:

 //在其他页面使用 import request from '../utils/wxAjax'
 //进一步封装-1.js
 export const QUERY_USER_INFO=(data = {})=> {
        return request({
            // baseURL: hostConfig.xxx,
            url: "/api/user/info",
            method: "GET",
            data,
        });
    },
 //使用-2.js
 import { QUERY_USER_INFO } from 'xxx'
 
  QUERY_USER_INFO({a:1}).then(res => {
    if(){}
  }).catch(err => {
    wx.showToast({
        title: err.message,
    })
})

方式二:

在小程序目录下建立 api 文件夹,并在文件夹下创建 api.js 脚本。下面开始封装 wx.request

const app = getApp()

const request = (url, options) => {
   return new Promise((resolve, reject) => {
       wx.request({
           url: `${app.globalData.host}${url}`,
           method: options.method,
           data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
           header: {
               'Content-Type': 'application/json; charset=UTF-8',
           },
           success(request) {
               if (request.data.code === 2000) {
                   resolve(request.data)
               } else {
                   reject(request.data)
               }
           },
           fail(error) {
               reject(error.data)
           }
       })
   })
}

const get = (url, options = {}) => {
   return request(url, { method: 'GET', data: options })
}
const post = (url, options) => {
   return request(url, { method: 'POST', data: options })
}
const put = (url, options) => {
   return request(url, { method: 'PUT', data: options })
}
// 不能声明DELETE(关键字)
const remove = (url, options) => {
   return request(url, { method: 'DELETE', data: options })
}

module.exports = {
   get,
   post,
   put,
   remove
}

使用封装过后的 api

import api from '../api/api'

api.post('/api/user/info', {
    data: ''
}).then(res => {
    console.log(res)
}).catch(err => {
    wx.showToast({
        title: err.message,
    })
})

post 请求就是api.post()…,get 请求就是api.get()…

方式三:

get请求直接传就可以了,post请求JSON.stringify(data)一下

const baseURL = 'https://some-domain.com/api/';
let header = {'content-type': 'application/json'};

function request(method, url, data) {
    return new Promise(function(resolve, reject) {
        wx.request({
            url: baseURL + url,
            method: method,
            data: method === POST ? JSON.stringify(data) : data,
            header: header,
            success(res) {
                //请求成功
                //判断状态码---errCode状态根据后端定义来判断
                if (res.data.errCode == 0) {
                    resolve(res);
                } else {
                    //其他异常
                    reject('运行时错误,请稍后再试');
                }
            },
            fail(err) {
                //请求失败
                reject(err)
            }
        })
    })
}

使用:
1,在小程序util文件夹下新建api.js,并将上述代码放进去然后创建请求,并导出

//导入request后
const API = {
    getOpenid: (data) => request(GET, `jsapi/mini?jsCode=${data}`),
};
module.exports = {
    API: API,
    // xxx,
}

2,这里我么以获取openid接口为例
在.js文件里引入api.js下的API

const $api = require('../../utils/api.js').API;
Page({
    data: {},
    onLoad: function (options) {
        wx.login({
            success:res=> {
                // 调用接口获取openid
                $api.getOpenid(res.code)
                    .then(res => {
                       //请求成功
                    })
                    .catch(err => {
                       //请求失败
                    })
            }
        })
    }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C+ 安口木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值