How does the mini program implement network requests (detailed process)

不言
Release: 2018-09-18 16:24:19
Original
3758 people have browsed it

The content of this article is about how small programs implement network requests (detailed process). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

For small programs, network request encapsulation is much more powerful than Android, which is worthy of praise. Official example:

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

but…but…This seems to be very simple to call, but something seems wrong? Something is wrong - too much code per call. Moreover, the log files of network requests are difficult to manage. This is still a bit far from our ideal approach.
So, what is our most ideal way to hope for?

1. The code is concise and can be done with one line of code.
2. Unified encapsulation and management of commonly used fields. Such as token, version number, etc.
3. Custom exception handling. If you are not logged in, you don't need to judge whether to log in, register, etc. every time you write an interface.

 api.request1(data, function (result) { //数据请求成功,
  },   function(error){//失败
 })
Copy after login

Then, based on the above question. Let me analyze it step by step.

1. Network request scenario analysis

1. Support token incoming network requests.

This situation is relatively rare. I encountered it in my current project. It probably means that administrators can operate other virtual users under their control. The administrator generates a token after logging in. Each time a member is generated, a virtual virtualToekn is generated. In the future, every time the administrator operates this member, he needs to use this virtualToken. However, when the administrator obtains his own information, he still needs to use his own token. At this time, it is necessary to support the incoming of custom tokens.

2. Hijacking of network requests.

There are two main situations in this scenario:

1. If the network fails
2. When there is no token, this scenario mainly appears in the login post-processing. For example, shopping cart app viewing shopping cart, etc.

Solution: Directly return failure, end this network request operation before initiating a network request, and reduce predicted erroneous network access

3. Support customization Pop-up and hiding control of the loading window

1. Pop-up of the loading window: There are many such scenarios. For example, when pulling down to refresh the list, the loading window does not need to appear. But getting user information requires loading to appear
2. Hiding the loading window: This scenario is if one interface is called successfully, and then the second interface is called continuously. In this way, after the first interface is successful, the loading window should not disappear, but should be hidden after the last interface is completed.

4. Handle different network errors

2. Code analysis

/**
 * 自定义token  请求
 * 
 * isShowLoading :true  弹出loading窗
 * isEndLoading: true  最后需要隐藏loading窗。若是false,则不隐藏
 * token: 可以自定义token。用户虚拟账号使用车辆
 */
 export function requestApi(requestData, isShowLoading = true,isEndLoading = true, token = null,onSuccess, onFail) {  
 let app = getApp().globalData;  // 1、检查是否已经登录,在未登录的时候,可以提前缓存一个临时token欺骗本次检查。等登录完成后,再更新token值
  if (!util.hasLogin()) {    return;
  }  // 2、检查网络状态
  if (!util.checkNetworkConnected()) { //没有网络
    onFail("网络请求失败,稍后再试")    return;
  }  if (!requestData) {
    onFail("数据异常,请稍后再试")    return;
  }  let cacheToken =  util.takeToken()  let newToken = token == null ? cacheToken : token
  console.log("newToken===========>", newToken)
  requestData.token = newToken
  requestData.version = app.version
  console.log("==================================================开始请求网络数据start========================================")
  console.log(requestData)
  console.log("==================================================开始请求网络数据end===========================================")  var baseUrl = app.debug ? app.debugUrl : app.releaseUrl    
  console.log("===baseUrl===>" + baseUrl)  if (isShowLoading){
    util.showLoading("加载中")
  }
  const requestTask = wx.request({
    url: baseUrl,    data: requestData,    header: {      'content-type': 'application/json'
    },
    method: 'POST',
    dataType: 'json',
    success: function(res) {
      console.log("==================================================返回请求结果start========================================")
      console.log(res.data)
      console.log("==================================================返回请求结果end===========================================")      
      if (res.data.code == 0) { //成功
        // console.log("onSuccess===========>", onSuccess);
        onSuccess(res.data)
      } else if (res.data.code == 1021) { //未缴纳押金
        wx.navigateTo({
          url: '/pages/recharge/recharge',
        })        return false;
      } else if (res.data.code == 1006) { //余额不足
        wx.navigateTo({
          url: '/pages/deposited/deposited',
        })        return false;
      } else if (res.data.code == 1019) { //未实名
        wx.navigateTo({
          url: '/pages/certify/certify',
        })        return false;
      } else if (res.data.code == 1001) { //token过期
        wx.reLaunch({
          url: '/pages/login/login'
        });        return false;
      } else { //失败
        let error = res.data == null || typeof (res.data) == "undefined" ? "网络请求失败,请稍后再试" : res.data.desc
        onFail(error)
        console.log("error===========>", error);
      }
    },
    fail: function(res) {
      console.log("onFail===========>", res);
      onFail("网络请求失败,稍后再试")
    },
    complete: function(res) {
      console.log("complete===========>", isEndLoading);      
      if (isEndLoading){
        wx.hideLoading()
      }
    }
  })
};
Copy after login

3. Unified switching of network environment.

Configure uniformly in app.json

  // 全局的数据,可以提供给所有的page页面使用
  globalData: {
    token: "",
    version: "version版本号",
    releaseUrl: "正式版url",
    debugUrl: "测试版url",    debug: true   //true  debug环境,false正式环境
  },
Copy after login

In this way, you only need to modify the debug value when switching network environments in the future.

4. Secondary Encapsulation

/**
 * 自定义loading  框请求
 * 
 * isShowLoading :true  弹出loading窗
 * isEndLoading: true  最后需要隐藏loading窗。若是false,则不隐藏
 */
 export function request(requestData, isShowLoading = true, isEndLoading = true, onSuccess, onFail){  
 this.requestApi(requestData, isShowLoading, isEndLoading, null, function (result) {
    onSuccess(result)
  }, function (error) {
    onFail(error)
  })
}/**
 *  带有loading 框的 不能自定义的请求
 * 
 */export function request1(requestData, onSuccess, onFail) {  // console.log("onSuccess========request1===>", success, fail);
  requestApi(requestData, true, true, null, function (result) {
    onSuccess(result)
  }, function (error) {
    onFail(error)
  })
}/**
 * 自定义token  请求
 * 
 * isShowLoading :true  弹出loading窗
 * isEndLoading: true  最后需要隐藏loading窗。若是false,则不隐藏
 * token: 可以自定义token。用户虚拟账号使用车辆
 */export function request2(requestData, isShowLoading = true, isEndLoading = true, token = null, onSuccess, onFail) {
  requestApi(requestData, isShowLoading, isEndLoading, token, function (result) {
    onSuccess(result)
  }, function (error) {
    onFail(error)
  })
}/**
 * 自定义loading  框请求
 * 
 * isShowLoading :true  弹出loading窗
 * isEndLoading: true  最后需要隐藏loading窗。若是false,则不隐藏
 */export function request3(requestData, isShowLoading = true, isEndLoading = true, token, onSuccess, onFail) {
  requestApi(requestData, isShowLoading, isEndLoading, token, function (result) {
    onSuccess(result)
  }, function (error) {
    onFail(error)
  })
}
Copy after login

end

Finally, the schematic diagram of viewing the log on the console is:
How does the mini program implement network requests (detailed process)

The above is the detailed content of How does the mini program implement network requests (detailed process). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!