原生微信小程序封装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);
       })
经验分享 程序员 微信小程序 职场和发展