微信小程序封装 request 请求

1、在小程序 utils 文件夹下新建 api.js

const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const FORM = 'FORM';
const DELETE = 'DELETE';

const baseURL = 'http://127.0.0.1:8081/';

function request(method, url, data) {
    return new Promise(function(resolve, reject) {
        let header = {
            // 'content-type': 'application/json'
            'content-type': 'application/x-www-form-urlencoded'
        };
        wx.request({
            url: baseURL + url,
            method: method,
            data: data,
            transformRequest: [ // 格式化data
                function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    ret = ret.substring(0, ret.lastIndexOf('&'));
                    return ret
                }
            ],
            header: header,
            success(res) {
                //请求成功
                //判断状态码---errCode状态根据后端定义来判断
                if (res.data.code == 0) {
                    resolve(res);
                } else {
                    //其他异常
                    reject('运行时错误,请稍后再试');
                }
            },
            fail(err) {
                //请求失败
                reject(err)
            }
        })
    })
}

// 接口请求
const API = {
    getDayList: (data) => request(GET, `day/list`),
};
// 导出
module.exports = {
    API: API
}

2、在页面js中导入请求工具类并调用

// 导入请求工具类
const $api = require('../../utils/api.js').API;
$api.getDayList()
  .then(res => {
    console.log(res.data, 111);
  })
  .catch(err => {
    console.log(err, 222);
  })

引用

https://www.jianshu.com/p/da32d38962e7

本文链接: https://jianz.xyz/index.php/archives/256/

1 + 8 =
快来做第一个评论的人吧~