封装小程序http请求

(一) promise封装一个请求接口
// 该文件为request.js
const host = 'http://localhost:8088/aaa/' // 域名
const request = (method, url, data, isLoading = true) => {
        if (isLoading) {
                wx.showLoading({
                        title: '加载中'
                });
        }
        var promise = new Promise(function(resolve, reject) {
                wx.request({
                        url: host + url,
                        data: data,
                        method: method,
                        header: {
                                "Content-Type": "application/json;charset=UTF-8",
                                //"userId":wx.getStorageSync('userId'),
                        },
                        success: function(res) {
                                if (isLoading) {
                                        wx.hideLoading();
                                }
                                if (res.status) {
                                        resolve(res.data);
                                } else {
                                        layerTip('网络错误');
                                }
                        },
                        fail: function(res) {
                                // fail调用接口失败
                                wx.hideLoading();
                        }
                })
        });
        return promise;
}

export request

(二) 写一个公共的调用接口的文件globalData.js

import {request} from './request'
 
//请求登陆接口
export const requestLogin = (loginName,password) => request('post','/api/doLogin',{loginName,password})

(三) 页面调用接口

// 局部引入需要的调用的接口
import {requestLogin} from './globalData.js'

// 对应的登录按钮方法里,调用接口,传入参数
login () {
        requestLogin(this.loginName,this.password).then(res => {
            if (res.status) {
                    wx.showToast({
                    title: '登录成功',
                    icon: 'success',
                    duration: 2000
                })
            }
       })
}