当前位置:网站首页>How to encapsulate the wx.request() request of WeChat applet

How to encapsulate the wx.request() request of WeChat applet

2022-08-02 10:12:00 Wang - Xiao Miao

Perform basic request encapsulation on wx.request() first, and then continue to encapsulate post and get requests

//in utils/http.js file/*** Request related packages*/let baseUrl = "http://xxx.xxx.xx.xx:xx/"; // interface addresslet header = {'content-type': 'application/x-www-form-urlencoded','Authorization': wx.getStorageSync("token")?wx.getStorageSync("token"):''}/*** package request*/function fetch(options) {if (options.loading) {wx.showLoading({title: 'Loading',mask: true})}return new Promise((resolve, reject) => {wx.request({url: baseUrl + options.url,data: options.data,header: header,method: options.method,success: function(res) {if (options.loading) {wx.hideLoading()}if (res.data.status != 0) { // Judge according to the return value of your own interface// re-loginreturn false;}resolve(res.data); //Send the requested data to the place where the request is referenced},fail: function(err) {if (options.loading) {wx.hideLoading()}wx.showToast({title: "Network connection timed out",icon: 'none',duration: 3000,})}})})}/*** POST request*/export function post(url, params, loading = true) {var option = {url: url,data: params,method: 'POST',loading}return fetch(option);}/*** GET request*/export function get(urls, params, loading = true) {var option = {url: urls,data: params,method: 'GET',loading}return fetch(option);}

Use

//First introduced through modularizationconst util = require('../../utils/util.js')//get requesthttp.get('getuserInfo', params).then((res) =>{console.log(res)})//post requesthttp.post('findDepartment', params).then( (res) =>{console.log(res);})// You can also use async and await, e.g.async formSubmit(e) {let params = {name: e.detail.value.namepassward:e.detail.value.passward}//let params = e.detail.valueconst res = await http.post('login',params)if(res.status====0){//Save the token and user information to the localwx.setStorageSync('token', res.token);wx.setStorageSync('userinfo', res.userinfo);wx.showToast({title: res.message,icon: 'none',duration: 3000});}}

原网站

版权声明
本文为[Wang - Xiao Miao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208021001115979.html

随机推荐