微信小程序封装wx.request请求

描述:为了将页面中的方法提取出来,因此对小程序请求进行二次封装。

  • api.js(公共请求)

      export const pubUrl = "https://xxx.com"//这是我要请求的数据接口的公共部分 
    
      const http = (options) =>{
        return new Promise((resolve,reject) => {
          wx.request({
            url: pubUrl + options.url,
            method: options.method || 'get',
            data: options.data || {},
            header: options.header || {
              // 'content-type': 'application/x-www-form-urlencoded',
              'content-type': 'application/json',
              Cookie: wx.getStorageSync("sessionid")
            },
            success: (res => {
              if (res.data.code === 0) {
                resolve(res.data)
              } else if (res.data.code === 401) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  complete: () => {
                    wx.navigateTo({
                      url: '/pages/login/index'
                    })
                  }
                })
              } else {
                resolve(res.data)
              }
            }),
            fail: reject
          })
        })
      }
      module.exports = {
          http
      }
    复制代码

根目录新建service文件夹,按模块新建js文件,将对应模块的接口请求放入其中,例如:

  • home.js(接口js文件,目录为service > home.js)

      import http from './api.js'
      
      // 营业时间列表
      const timelist = () => {
        return http({
          method: 'get',
          url: '/merchant/openTime/'
        })
      }
      
      module.exports = {
          timelist
      }
    复制代码

使用:home > index.js(页面js文件)

   import { timelist } from '../home'
   
   Page({
       onLoad() {
           this.getData()
       },
       async getData() {
           const {code, data, msg} = await timelist()
       }
   })
   
复制代码

image.png

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享