preface
Applet native Wx. request is cumbersome and prone to callback hell, which is not conducive to maintenance. Promise is used to encapsulate the small program request, and then encapsulate the global call of the wrapper request function reqWrapper, which greatly reduces the amount of code and improves the maintainability. (Note that the following is written in TS and can be changed to JS as required)
Request elegance VS native request:
// If the cgi fails, the ret_msg error field pops up by default
API.getTest(entryData).then((res: any) = > {})
.catch((err: string) = > {
console.error(err)
})
-----------------------------------------------------------------------------------------
// Native request
wx.request({
url: 'test.php'.// This is an example, not a real interface address
data: {
x: ' '.y: ' '
},
method: 'POST',
success (res: any) {
console.log(res.data)
},
fail (res: any) {
console.log(res.data)
})
Copy the code
So what do we need to do?
First, introduce the network request component weRequest of logon state management
WeRequest, a log-in state management network request component developed by a big man in the company, solves the tedious small program session management, specific can be moved to learn. Configure Request. ts as instructed.
let weRequest = require('./weRequest.js');
weRequest.init({
// [Required] The back-end interface returns the third-party login status after successful login
getSession: function (res: any) {},
// [required] Exchange code for session CGI configuration
codeToSession: {
// [required] CGI URL
url: ` `.// [required] The session value returned from CGI
success: function (res: any) {}},// [Required] Conditions that trigger re-login. Res is the data returned from CGI
loginTrigger: function (res: any) {
// In this example, if the errcode field in the returned data is -1, the system automatically triggers a re-login
},
// Number of login retries. If the number of consecutive login attempts returned by the interface exceeds this number, the login will not be retried
reLoginLimit: 2.// Triggers a request success condition
successTrigger: function (res: any) {
// In this example, if ret_code in the returned data is 0, the request succeeds. In other cases, the service logic fails
return res.ret_code == 0;
},
// Return data on success; Don't preach
successData: function (res: any) {
// In this example, the returned data field data is the data received by the service
return res;
},
// When CGI returns an error, the popup prompts the title text
errorTitle: function () {
return 'Operation failed'
},
// When CGI returns an error, the popup prompts the content text
errorContent: function (res: any) {
return (res.msg ? res.ret_msg : 'Operation failed');
},
doNotUseQueryString: true
});
export default weRequest
Copy the code
Wrap the package request function
- 1. Import the configuration file request.ts in step 1
import weRequest from '.. /lib/request'
Copy the code
- 2. Encapsulate the wrapping function
/** * wrap function *@param Opts weRequest parameter *@param Data Interface parameter *@param Url CGI path *@param ReqOpts request mode. The default value is POST. */ is optional
let reqWrapper = (data: object, url: string, reqLoad? : boolean, reqOpts? : string) = > {
let param = Object.assign({}, data)
return weRequest.request(Object.assign({}, {
url: url,
data: param,
method: reqOpts? reqOpts : 'POST'.showLoading: reqLoad? reqLoad : false // When true, the cgi will be requested to load}}))export default {
// Export the request, for example
saveTest(opts: RequestBody.saveTest): Promise<ResponseBody.saveTest> {
return reqWrapper(opts, url , true)}},Copy the code
3. Custom error notification
After wrapping the request function, we set the condition successTrigger to trigger the request success in the first step request.ts, as well as the default error pop-ups errorTitle and errorContent. Therefore, once we report an error on the interface, the error popover will be triggered by default, and we cannot catch an ERR error in the catch, but weRequest provides a custom error handling function fail. We can encapsulate our function like this:
/** * wrap function *@param Opts weRequest parameter *@param Data Interface parameter *@param Url CGI path *@param ReqOpts Request mode. The default value is POST@param FaliReport specifies whether the XXX function is available. Optional */
let reqWrapper = (data: object, url: string, faliReport? : any, reqLoad? : boolean, reqOpts? : string) = > {
let param = Object.assign({}, data)
return weRequest.request(Object.assign({}, {
url: url,
data: param,
showLoading: reqLoad ? reqLoad : false.// Whether loading is displayed during the request
method: reqOpts ? reqOpts : 'POST'.fail: faliReport ? function () { faliReport() } : ' '}}))export default {
// Export the request, for example
saveTest(opts: RequestBody.saveTest, faliReport: unknown): Promise<ResponseBody.saveTest> {
return reqWrapper(opts, url , faliReport)
},
}
Copy the code
Based on the above encapsulation, we can pass in the XXX function that we want to customize the error message when calling the function, so we can customize the error message
Four, small program page use
- 1. Add the step 2 file, such as api.ts, to the corresponding page
import API from ".. /.. /api";
Copy the code
- 2. The request format is as follows
Page({
data: {},
onLoad(query: any) {
this.test()
},
test: function () {
const self = this;
let entryData: RequestBody = {};
let testErrorFunction = self. testErrorFunction; // If you want to customize the error, pass in the function XXX
API.getTest(entryData, self.testErrorFunction).then((res: any) = > {})
.catch((err: string) = > {
console.error(err)
})
},
// custom error XXX function
testErrorFunction: function () {
console.long('error')}})Copy the code