Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How the native Mini Program of js encapsulates the request and calls the API gracefully

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how js native Mini Program encapsulates requests to call the interface gracefully". Many people will encounter this dilemma in the operation of practical cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Encapsulate Promise-style requests based on Mini Program native request

Avoid multi-level callbacks (callback hell)

Unified processing and distribution for network request errors

Directory structure. ├── api │ ├── config.js / / related request configuration items, request api and other │ ├── env.js / / environment configuration │ ├── request.js / / encapsulate the main function │ ├── statusCode.js / / status code └──. Related code configuration file env.js// env.jsmodule.exports = {ENV: 'production', / / ENV:' test'} statusCode.js// statusCode.js// configure some common request status codes module.exports = {SUCCESS: 200 EXPIRE: 403} config.js// config.jsconst {ENV} = require ('. / env') let BASEURLswitch (ENV) {case 'production': BASEURL =' 'break case' test': BASEURL =''break default: BASEURL =' 'break} module.exports = {BASEURL,// project interface address Support multiple domain names} main function

Note that line 64: 68 deals with the expiration of token. When calling login, check whether token exists in app.globalData. If it exists, no login request will be made. If token expires, the token will be cleared, and the next request will be re-initiated and the new token will be re-obtained.

/ / introduce the status code statusCodeconst statusCode = require ('. / statusCode') / / define the request path, BASEURL: general request API CBASEURL: CCTV API, CBASEURLconst {BASEURL} = require ('. / config') / / define default parameter const defaultOptions = {data: {}, ignoreToken: false, form: false } / * send request * @ params * method: request method: POST/GET * url: request path * data: request parameter * ignoreToken: whether to ignore token verification * form: whether to use formData request * / function request (options) {let _ options = Object.assign (defaultOptions, options) let {method, url, data, ignoreToken Form} = _ options const app = getApp () / / set request header let header = {} if (form) {header = {'content-type':' application/x-www-form-urlencoded'}} else {header = {'content-type':' application/json' / / Custom request header Information}} if (! ignoreToken) {/ / from the global variable Get token let token = app.globalData.token header.Authorization = `Bearer ${token} `} return new Promise ((resolve) in Reject) = > {wx.request ({url: BASEURL + url, data, header, method Success: (res) = > {let {statusCode: code} = res if (code = statusCode.SUCCESS) {if (res.data.code! = = 0) {/ / Unified processing request error showToast (res.data.errorMsg) reject (res.data) return} resolve (res.data )} else if (code = statusCode.EXPIRE) {app.globalData.token =''showToast (`login expires) Please refresh the page `) reject (res.data)} else {showToast (`request error ${url}, CODE: ${code}`) reject (res.data)}}, fail: (err) = > {console.log ('% c err', 'color: red) Font-weight: bold', err) showToast (err.errMsg) reject (err)})} / / encapsulates the toast function function showToast (title, icon='none', duration=2500, mask=false) {wx.showToast ({title: title | |', icon, duration, mask}) } function get (options) {return request ({method: 'GET',... options})} function post (options) {/ / url, data = {}, ignoreToken, form return request ({method:' POST',... options})} module.exports = {request, get, post} use the method to create a new file

Create a new api file (here take the order API as an example) and create a new api/index.js (API distribution is handled uniformly to prevent the API from being too lengthy to write to the same file)

The directory structure is as follows:

. ├── api │ ├── config.js / / related request configuration items, request api and other │ ├── index.js / / unified processing entry │ ├── order.js / / order interface │ ├── request.js / / encapsulates the main function │ ├── statusCode.js / / status code └──. Introduce request// order.jsconst request = require ('. / request') module.exports = {/ / data can pass url, data, ignoreToken, form, cToken apiName (data) {let url = 'apiUrl' return request.post ({url, data})}} unified distribution interface const orderApi = require (". / order") module.exports = {orderApi} page reference const {orderApi} = require (' dir/path/api/index'). 1. `Promise.then ()` chain call func () {orderApi.apiName (params) .then (res = > {/ / do Something}) .catch (err = > {/ / do Something})} 2. `async/ await` calls async func () {try {let res = await orderApi.apiName (params) / / do Something} catch (err) {/ / do Something}} options value parameter indicates that the data type default value url Oral name String''data request body Object {} ignoreToken request whether to carry tokenBooleanfalseform is a form request Booleanfalse "how does the native Mini Program encapsulate the request to call the interface gracefully?" that's it. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report