微信小程序 wx.request 封装及使用

第一步:在在util文件夹中,新建一个文件api.js

const GET = GET;
const POST = POST;
 
const baseURL = https://www.zzgoodqc.cn;//配置的域名
 
function request(method, url, data) {
    return new Promise(function(resolve, reject) {
        let header = {
            content-type: application/json,
        };
        wx.request({
            url: baseURL + url,
            method: method,
            data: method === POST ? JSON.stringify(data) : data,
            header: header,
            success(res) {
                //请求成功
                //判断code是否为0表示成功
                if (res.data.code == 0) {
                    resolve(res);
                } else {
                    //其他错误
                    //reject(运行出错,请稍后再试);
                    console.log(res.data.msg);
                    wx.showToast({   //弹出框
                        title: res.data.msg,
                        icon: error,
                        duration: 2000
                      });
                }
            },
            fail(err) {
                //请求失败
                reject(err)
            }
        })
    })
}
 
 
//接口可以集合到一块,集中管理
const API = {
register: (data) => request(POST, `/index.php/index/index/register`,data),  //注册
  getLogin:(data)=>request(POST,/index.php/index/index/login,data),   //登录
  getstrcode:()=>request(GET, `/index.php/index/index/getcode`)      //验证码
  
};
module.exports = {
  API: API
}

第二步:使用封装的代码,在需要请求接口的地方,引入当前文件

在js文件顶部引入(需要在哪个js文件下调用接口,就放在哪个文件下)

const $api= require(../../utils/api).API

调用接口

// get请求
$api.getstrcode().then(res=>{
    console.log(res);
    if(res.data.code==0){

    }
}).catch(err=>{
    console.log(err);
})

//post请求
let obj={
    name:,
    pwd:,
    vercode:,   //验证码
};
$api.getLogin(obj).then(res=>{
    console.log(res);
    if(res.data.code==0){

    }
}).catch(err=>{
    console.log(err);
})

catch也可以不写,看情况使用

注意:

经验分享 程序员 微信小程序 职场和发展