微信小程序 封装请求api

封装请求地址 https.js

js 复制代码
 let baseUrl='https://XX.XXX.com/index.php/'; //自己得服务器地址
 export {
    baseUrl
  }

结构目录

封装 request.js

js 复制代码
import { baseUrl } from './https.js'
 
module.exports = {
  request : function(url, methodType, data){
    let fullUrl = `${baseUrl}${url}`
    // let token = wx.getStorageSync('token') ? wx.getStorageSync('token')  : ''
    //(wx.showLoading)显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({ title: "数据请求中"  });
    return new Promise((resolve,reject)=>{
      wx.request({
        url: fullUrl,
        method:methodType,
        data:data,
        header: {
          'content-type': 'application/json', // 默认值
          // 'x-api-key': token,
        },
        success(res){
            resolve(res)
        //   if (res.data.status == 200) { //根据自己返回数据状态进行更改
        //     resolve(res.data)
        //     wx.hideLoading()
        //   }else{
          //手动关闭loading提示框
            wx.hideLoading()
        //     wx.showToast({
        //       title: res.data.msg,
        //       icon:'none'
        //     })
        //     reject(res.data.message)
        //   }
        },
        fail(){
          wx.showToast({
            title: '接口请求错误',
            icon:'none'
          })
          reject('接口请求错误')
        }
      })
    })
  }
}

自己的js文件构造

js 复制代码
import { request } from './request'
 
module.exports = {
  // 获取采购list
  getPurchaseList: (data) => request('api/Api/list', 'POST', data),
}

如何调用

js 复制代码
const api = require('../../../api/purchase'); // 头部引入


  getPurchaseList(){
    var that = this;
    let data ={
     "openId": that.data.userInfo.app_openid,
     "token": that.data.userInfo.login_token
    };
    api.getPurchaseList(data).then((res) => {
			    if (res.data.status == 1) {
			                    that.setData({
			            goodsTypes: res.data
			        })
                } else {
                    app.myShowToast(res.data.msg);
                }
       
    })
  },
相关推荐
WangHappy1 天前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端2 天前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
icebreaker3 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker3 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
大米饭消灭者5 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro
FliPPeDround6 天前
Vitest Environment UniApp:让 uni-app E2E 测试变得前所未有的简单
微信小程序·e2e·前端工程化
FliPPeDround6 天前
微信小程序自动化的 AI 新时代:wechat-devtools-mcp 智能方案
微信小程序·ai编程·mcp
吴声子夜歌7 天前
小程序——布局示例
小程序
码云数智-大飞7 天前
如何创建自己的小程序,码云数智与有赞平台对比
微信小程序
luffy54597 天前
微信小程序页面使用类似filter函数的wxs语法
微信小程序·小程序