微信小程序 封装请求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);
                }
       
    })
  },
相关推荐
黑客老李9 小时前
web渗透实战 | js.map文件泄露导致的通杀漏洞
安全·web安全·小程序·黑客入门·渗透测试实战
游戏开发爱好者819 小时前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
2501_9151063221 小时前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_9151063221 小时前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
宠友信息1 天前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
“负拾捌”1 天前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别
换日线°2 天前
NFC标签打开微信小程序
前端·微信小程序
光影少年2 天前
AIGC + Taro / 小程序
小程序·aigc·taro
2501_915918412 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
2501_916007472 天前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview