微信小程序ajax请求封装

虽然小程序有自己的ajax请求封装,但是写多了代码就比较冗余,我们可以基于小程序的ajax请求去自己封装promise请求,这样可以使代码看起来更加的简洁,同时还能解决一些因为异步请求带来的问题。

在app.js中添加接口封装方法

ajax(method, url, option){
        wx.showLoading({
            title: '加载中...'
        });
        let methodType = 'application/json';
        if(method=='POST'){
            methodType = 'application/x-www-form-urlencoded'
        }
        let urlHead='https://xxx.com/'  //请求头
        let requestUrl=urlHead+url;
        return new Promise((resolve,reject)=>{
            wx.request({
                url: requestUrl,
                method:method,
                data:option,
                header: {
                    'content-type': methodType 
                },
                success:res=>{
                    wx.hideLoading();
                    let statusCode = res.statusCode
                    if (statusCode >= 200 && statusCode < 300)  {
                        resolve(res.data)
                    } else {
                        console.log('请求失败')
                        wx.showToast({
                            icon:'none',
                            title: res.data.message
                        });
                        reject(res.data)
                    }
                },
                fail:err=>{
                    console.log(err)
                }
            });
        })
    },

页面中调用时

const app = getApp();
import regeneratorRuntime from '../../libs/runtime.js'  //这个很重要

//经过微信开发者工具的不断升级,
//它的“ES6转ES5”的功能也渐渐有了加强,
//所以要用async/await的话,已经不需要如本文中描述的使用额外的gulp和babel来自己做预编译工作,
//只需要引入regenerator runtime就可以了。


Page({

    onLoad(){
        this.testMethod()
    }
    
    async testMethod(){
        let url="/xxx"
        let data = await app.ajax('GET',url,{data:123});
        console.log(data)
    }

})

猜你喜欢

转载自blog.csdn.net/weixin_41587194/article/details/101014441