Home >WeChat Applet >Mini Program Development >Self-study WeChat applet from zero to one: http request encapsulation after project construction

Self-study WeChat applet from zero to one: http request encapsulation after project construction

hzc
hzcforward
2020-06-12 10:08:582585browse

1. http module repackage

First of all, why should we repackage WeChat’s http module? Let’s first take a look at how WeChat’s built-in http request is written.

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {    'content-type': 'application/json' // 默认值
  },
  success (res) {
    console.log(res.data)
  }
})

This request method is similar to our ancient jquery method. We need to do some business operations in the success callback function. This method will cause our callback hell problem, and the code is not intuitive enough. And the code is too cumbersome;

Next I will package the code through promises and simplify the request method

1. Project directory construction

Self-study WeChat applet from zero to one: http request encapsulation after project construction

Create the request.js file under the utils directory to encapsulate http requests. We encapsulate through promises. This is helpful for us to handle errors, and we can also view the business logic very intuitively. The encapsulated sample code is as follows:

/**
 * 
 * @param {String} url 
 * @param {Object} data 
 * @param {String} method 
 * @param {String} header 
 */
function request(url, data={}, method='GET', header="Content-Type: application/json",) {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: url,
            data: data,
            header: header,
            method: method,
            dataType: 'json',
            responseType: 'text',
            success: (res)=>{
                if(res.statusCode === 200) {
                    if (res.data.code === 200) {
                        resolve(res.data)
                    } else {
                        wx.showToast({
                            title: res.data.msg,
                            icon: 'none',
                            image: '',
                            duration: 1500,
                            mask: false,
                            success: (result)=>{
                                resolve(res.data);
                            },
                        });
                    }
                } else {
                   
                }
            },
            fail: (res)=>{
                // 需要我们加上统一的错误处理代码
                reject(res)
            },
            complete: ()=>{}
        });
    }) 
}

// 封装方法
// 如果对于header有什么特殊的要求,可以在请求参数里面做一些添加,例如后续我们会在headder中加入我们的sessionkey这些内容
// header = {}里面添加header内容
// 这块是一个简版的说明
const header = {
    "Content-Type": "application/json",
    // 这个token是微信登录以后,将token存入在缓存中
    "token": "*****************"
}

const get = function(url, data, header) {
    return request(url, data, 'GET', header);
}

const post = function(url, data, header) {
    return request(url, data, 'POST', header);
}

const del = function(url, data, header) {
    return request(url, data, '', header);
}


module.exports = {
    get,
    post,
    del,
}

2. The use of requests in the project

First We introduce our encapsulated http module at the location of use

import webHttp from './utils/request';

Next we can use our encapsulated webhttp tool, which reduces the amount of code compared to the previous direct use of WeChat's request request method. At the same time, the chain method makes The logic is clearer

webHttp.get(api.user.info, {
    // nick_name: 
    ...self.globalData.userInfo
}).then((res) => {
    console.log(res);
})

It is roughly a process like this. In the actual process, the encapsulation may need to be further improved according to the back-end restful api method. The data parameters of the post request are also processed differently. This needs Make corresponding adjustments according to the actual situation. If this article is helpful to you, you are welcome to save it and like it. If there is a better way, you are welcome to communicate. Progress will never stop.

Recommended tutorial: "WeChat Mini Program

The above is the detailed content of Self-study WeChat applet from zero to one: http request encapsulation after project construction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete