I. Main functions

  1. Automatic garbage cleanup request: Suppose the applet has three pages, A, B, and C, and each page initiates A request. NavigateBack from page C or the user manually swiping back to page B automatically terminates pending requests from page C to release resources. SwitchTab from PAGE C to page A automatically terminates pending requests from page B and page C. The principle is to bind the initiated requests to the page, and then listen for the onUnload event of the page. When the page is unloaded, the uncompleted requests are stopped, or the page can be unbound by parameter configuration.

  2. Change the request form to PROMISE: Encapsulate the request mode of native applet into promise mode.

  3. Limit the number of concurrent requests: the small program limits the number of concurrent requests to 10, exceeding which an error will be reported. This code queues requests and configures the number of concurrent requests.

  4. Automatic re-login after the token expires: You can configure the interface to automatically re-log in when certain situations are returned. After you log in to the system again, previous requests are automatically resend. This process is not perceived by users, which improves user experience.

  5. Add retry: The request API of the applet occasionally fails, and the network status on the mobile side is not as stable as that on the PC side, since the device may be on the move, it is best to add retry. One method of reproduction is to write an interface with slow response, and then frequently switch the network of the mobile phone from wifi state to 4G when the request is made. That is, the wifi switch is repeatedly turned on and off when the request is made. The interface will not respond successfully every time. This code can configure the number of retries of the interface. Request problems found in the community.

  6. Cancel request: You can cancel common request and upload and download request

  7. You can configure whether an interface requires authentication: If authentication is required, the interface is invoked in advance even if the login interface is not actively invoked. Even if multiple authentication interfaces are requested concurrently, the program will automatically execute the login interface only once, so that there is no need to worry about the problem of repeated login. Assume that there are two tabBar pages A and B. Page A is the home page and has login logic. The user switches to page B before completing the login

  8. Compatible with uni – app

Two, the way of use (can run code reference)

  1. Import mixin.js in app.js (always import in app.js).
  2. Uni-app needs to import mixin.js in the API directory of uniapp-demo (must be imported in main.js).
  3. Import wxRequest. Js
  4. Initialize wxRequest with the following parameters. The parameters without default values are mandatory

baseUrl

  • Type: String
  • Default value: none
  • Usage: Prefix of an interface

loginUrl

  • Type: String
  • Default value: none
  • Usage: indicates that the login interface is the concatenation of two strings baseUrl + loginUrl
  • Example: baseUrl is http://127.0.0.1:3001/ loginUrl is login. Then said the login interface is http://127.0.0.1:3001/login

resolveData

  • Type: the function
  • Default value: none
  • Usage: a method that returns a value in response to data retrieved by the interceptor, i.e. the caller then
  • Example: Suppose the interface returns {“code”:0,”data”:{“message”:” Hello world/version? Id =a0″}} The front end only wants data from data, so set it like this
function(data) {
    return data.data // Response interceptor, i.e., then fetch data
}
Copy the code

getToken

  • Type: the function
  • Default value: none
  • Usage: a method with a return value that tells the code how to get the token returned by the login interface
  • Example: If the return value of the login interface is {“code”:0,”data”:{“access_token”:”001″}} To obtain the token set this way
function(data) {
    return data.data.access_token
}
Copy the code

reqSuccess

  • Type: the function
  • Default value: none
  • Usage: Need to return true and false to tell the code under what circumstances is the value returned by the interface successful
  • Example: If the code returned by the interface must be 0 and have a data value for success, set this
function(data) {
    if (data && data.code === 0 && data.data) {
        return true
    }
    return false
}
Copy the code

reacquire

  • Type: the function
  • Default value: none
  • Usage: Need to return true and false to tell the code when to log back in
  • Example: If the code is 401 or 402, the token has expired and needs to be re-logged in, then set it like this
function(data) {
    if (data && [401.402].includes(data.code)) {
        return true
    }
    return false
}
Copy the code

authorization

  • Type: String
  • Default value: Authorization
  • Usage: The key value passed to the backend token, placed in the header of the request

limit

  • Type: Number
  • Default value: 5
  • Usage: Indicates the maximum number of concurrent requests, including uploads and downloads

loginRetry

  • Type: Number
  • Default value: 2
  • Usage: Number of retries in case of login interface exception, not retries in case of server error (server error means something like 500 error)

retry

  • Type: Number
  • Default value: 2
  • Usage: retry several times when an error occurs on an interface other than the login interface. If the server fails, it will not retry. (Upload and download are not retried, because upload and download are rarely used and appear to fail.)

  1. After initializing the wxRequest instance, it’s time to call its API

Three, API

token

  • Type: the property
  • Usage: Obtain the token after login

ajax

  • Type: the function
  • Usage: Initiate a request
  • Parameters:
  1. Data: The object type, like data in the applets request API, is a parameter passed to the server
  2. Url: A string that is preceded by a concatenated baseUrl to form the request address
  3. Type: a string. The default value is GET, which is consistent with the method parameter in the apPLETS API
  4. Page: a string indicating which page this request is associated with. If not, it is the last route path in the array returned by wechat API getCurrentPages(). If you do not want the interface and the page bound together, you can enter a value that is not a route
  5. WhiteList: Boolean type. True indicates that users can access the IP address only after logging in. False indicates that users can access the IP address without logging in

upload

  • Type: the function
  • Usage: Upload a file
  • Parameter: Object, which has the following properties
  1. Page: a non-mandatory String. If this parameter is not specified, it indicates a route
  2. Url: upload address
  3. FilePath: indicates the local address of the file
  4. Name: The name of the uploaded file is consistent with the parameter of the applet
  5. OnProgressUpdate: optional Function, upload progress callback Function

download

  • Type: the function
  • Usage: Download a file
  • Parameter: Object, which has the following properties
  1. Page: a non-mandatory String. If this parameter is not specified, it indicates a route
  2. Url: the download address
  3. OnProgressUpdate: optional function, callback function for downloading progress

login

  • Type: the function
  • Usage: Actively invoke login
  • Parameters: no

cancelAllRequest

  • Type: the function
  • Usage: Cancel all requests of the applet
  • Parameters: no

cancelRequest

  • Type: the function
  • Usage: Cancel a request
  • Parameter: requestId in promise returned with Ajax (can run demo applet, cancel button on home page)

cancelPageRequest

  • Type: the function
  • Usage: Cancel a request for a page
  • Parameter: A string, which can be the path of a route or the page parameter passed at the beginning of the Ajax call

getErrMsg

  • Type: the function
  • Usage: Extract error information, used in catch to get information about an error
  • Parameter: Error information, which can be an object or a string. You need to modify the parameter based on the actual service because not all cases can be taken into account

Four, test,

  1. Using the code in the Node-server provided with the project, NPM install installs the dependencies and then starts the Node server using NPM run dev
  2. If you want to simulate retry, simply do not start the Node server so that the login request will be retried
  3. To simulate login authentication failure, change the code of the /version interface in Node-server to 401
  4. Changing the Node-server code midway will automatically restart the server. You can modify the return of the interface at any time, and you can test whether the applet will log in again if it encounters a 401 condition in the middle of the running process. Shut down the server halfway and see if it retries. Restart the server during the retry to see if the retry succeeds

5. Warehouse address

Github.com/lijibing01/…

  • Welcome to star