1. Preface
When I was connecting with my partners today, I opened the compression package and found that there were big problems with the project. There was no login verification request in the project to encapsulate interceptors. When developing mini programs, it is undoubtedly quite troublesome to maintain them. In fact, we usually need to encapsulate network requests and interceptors to achieve unified processing of status codes and storing user login information and other functions. This can improve development efficiency, reduce code duplication, and also improve code maintainability and readability.
2. Ideas
Encapsulate network requests
First, network requests need to be encapsulated, responsible for sending requests and processing responses. This class should contain the following methods:
·request(url, method, data, header): Send a network request and return the response result.
·get(url, data, header): Send a GET request.
·post(url, data, header): Send a POST request.
Different request methods
Network requests can be implemented using the methods provided by the applet, and the parameters of the method correspond one by one to the parameters of the above method. When processing responses, you can use the Promise object to handle asynchronous operations.
Unified processing of status codes
Can create acheckStatus
Function, used to uniformly process status codes. This function accepts a response parameter to determine whether the request is successful. If the request is successful, return aPromise
object so that we can perform subsequent operations. If the request fails, an error is thrown.
Create an interceptor class
See below for specific processing logic.
2.1 Encapsulate network requests
Encapsulate a request function to send requests. This function accepts an argument options to configure the request. We can use the applet provided in this functionThe interface sends a request and returns a Promise object after the request is completed, so that we can perform subsequent operations.
function request(options) { return new Promise((resolve, reject) => { ({ url: , method: || 'GET', data: || {}, header: || {}, success: resolve, fail: reject }) }) }
2.2 Unified processing of status codes
We can encapsulate onecheckStatus
Function, used to uniformly process status codes. This function accepts a response parameter to determine whether the request is successful. If the request is successful, return aPromise
object so that we can perform subsequent operations. If the request fails, an error is thrown.
function checkStatus(response) { const { statusCode, data } = response if (statusCode >= 200 && statusCode < 300) { return (data) } else { const error = new Error(`Request failed,Status code:${statusCode}`) = response throw error } }
2.3 Encapsulation Interceptor
We can encapsulate oneinterceptor
Function, used to encapsulate interceptors. This function accepts a chain parameter to execute the interceptor chain. We can define a functionrequestInterceptor
And oneresponseInterceptor
, an interceptor used to process requests and responses separately. We canrequestInterceptor
Set the request header in the following requests to facilitate authentication. We canresponseInterceptor
The status code is uniformly processed and the user login information is updated when the request is successful.
function interceptor(chain) { const requestInterceptor = (options) => { // Set request header = 'Bearer ' + getApp(). return (options) } const responseInterceptor = (response) => { const { statusCode, data } = response if (statusCode >= 200 && statusCode < 300) { // Update user login information getApp(). = } else { const error = new Error(`Request failed,Status code:${statusCode}`) = response throw error } return response } return { request: requestInterceptor, response: responseInterceptor } }
2.4 Compatible with different request methods
//The code for encapsulating put request method is as follows:function put(options) { return new Promise((resolve, reject) => { ({ url: , method: 'PUT', data: || {}, header: || {}, success: resolve, fail: reject }) }) } //The code for encapsulating the delete request method is as follows:function del(options) { return new Promise((resolve, reject) => { ({ url: , method: 'DELETE', data: || {}, header: || {}, success: resolve, fail: reject }) }) } //The code for encapsulating the post request method is as follows:function post(options) { return new Promise((resolve, reject) => { ({ url: , method: 'POST', data: || {}, header: || {}, success: resolve, fail: reject }) }) }
2.5 Global storage of user login information
We can define a global variable in the appletglobalData
, used to store user login information. We can save user information to this variable after login is successful and use this variable for authentication in subsequent requests.
App({ globalData: { userInfo: null, token: null } })
2.6 Complete code
// function request(options) { return new Promise((resolve, reject) => { ({ url: , method: || 'GET', data: || {}, header: || {}, success: resolve, fail: reject }) }) } function put(options) { return new Promise((resolve, reject) => { ({ url: , method: 'PUT', data: || {}, header: || {}, success: resolve, fail: reject }) }) } function del(options) { return new Promise((resolve, reject) => { ({ url: , method: 'DELETE', data: || {}, header: || {}, success: resolve, fail: reject }) }) } function post(options) { return new Promise((resolve, reject) => { ({ url: , method: 'POST', data: || {}, header: || {}, success: resolve, fail: reject }) }) } function checkStatus(response) { const { statusCode, data } = response if (statusCode >= 200 && statusCode < 300) { return (data) } else { const error = new Error(`Request failed,Status code:${statusCode}`) = response throw error } } function interceptor(chain) { const requestInterceptor = (options) => { = 'Bearer ' + getApp(). return (options) } const responseInterceptor = (response) => { const { statusCode, data } = response if (statusCode >= 200 && statusCode < 300) { getApp(). = } else { const error = new Error(`Request failed,Status code:${statusCode}`) = response throw error } return response } return { request: requestInterceptor, response: responseInterceptor } } export { request, put, del, post, checkStatus, interceptor }
3. Use examples
import { request, interceptor, checkStatus } from './request' const chain = interceptor({ request: (options) => { ('Request Interceptor') return options }, response: (response) => { ('Response Interceptor') return response } }) request({ url: '/api/users', method: 'GET' }) .then(checkStatus) .then(data => { (data) }) .catch(error => { (error) })
4. Things to note
① When using an interceptor, you need to pay attention to the execution order of the interceptor. In the above example, the order in which the interceptor is executed is to execute the request interceptor first, and then the response interceptor is executed.
② In a mini program, we can use the getApp() function to get the mini program instance and access global variables.
③ When sending a request, you need to pay attention to the parameter configuration of the request. In the above example, the default GET request method and empty object are used as request parameters, and the common request method is configured. If you need to use other request methods or custom request parameters, please make the corresponding configuration when calling the request function.
5. Conclusion
In fact, the requested url address can also be encapsulated separately. You need to create a new JS file to export the domain name or url address, and then call the request to encapsulate the place, import it. The above is all about the mini program encapsulating network requests and interceptors. I hope it can help friends in need. Welcome everyone to communicate and make progress together~
This is the article about the practical steps of encapsulating network requests and interceptors of WeChat applets. For more relevant applets packaging network requests and interceptors, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!