原生微信小程序封装request

request文件

// 封装请求
const baseURL = 'https://api-hmugo-web.itheima.net/api/public/v1'
const request = (options) => {
    // return new Primise才可以使用then或者async 
    return new Promise(function(resolve, reject) {
        let header = {'content-type': "application/x-www-form-urlencoded"}
    wx.request({
        url: baseURL + options.url,
        data: options.data,
        header ,
        method: options.method,
        timeout: 10000,
        success: (result) => {
            // 请求成功的回调
            /* 在这里可以做状态码判断
               并给对应的状态码一些行为
               此处由于接口的原因,我直接返回了
            */
            resolve(result.data);
        },
        fail: (err) => {
            // 请求失败的回调
            wx.showToast({
                title: '网络连接失败',
                icon: 'none',
                duration: 1000
              })
              //请求失败
              reject(err)
        }
      })
    })

} 
export {request} 

抽离的接口请求文件

import { request } from '../utils/request' 
// 商品详情
export function goodsDetail (data) {
    return request({
      url: '/goods/detail',
      method: 'get',
      data
    })
}

在页面里使用

import { goodsDetail } from '../../server/goodsDetail'


goodsDetail({goods_id}).then(res=>{
           console.log(res);
       })
posted @   兔子先森Ace  阅读(79)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示