微信小程序 - 请求超时,简单封装 wx.request

配置 networkTimeout

app.json 文件设置超时时间--文档

"networkTimeout": {
    "request": 20000 
 }

wx.request时超时会进入fail方法

简单封装

配置app.js

globalData: {
    userInfo: null,
    host:'https://aaa.com.cn/'
}

api.js

const app = getApp()

const request = (url, options) => {
  wx.showLoading({
    title: '加载中',
    mask: true 
  })
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.host}${url}`,
      method: options.method,
      data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
        // 'token': wx.getStorageSync("token")
      },
      success(request) {
        if (request.data.success == true) {
          resolve(request)
        } else {
          reject(request)
        }
      },
      fail(error) {
        reject(error)
      },
      complete: info => {
        wx.hideLoading()
      }
    })
  })
}
const get = (url, options = {}) => {
  return request(url, { method: 'GET', data: options })
}
module.exports = {
  get
}

调用

const api = require('路径/api.js')
api.get("api/a/a.do?c=" + options.id).then(res => {
    ... 
}).catch(err => {
      ...
});

参考:
https://www.jianshu.com/p/db19fabe9a01
https://www.jianshu.com/p/ad1e5b581e18

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容