微信小程序api封装方案

创建fetch.js封装requset请求

const BaseUrl= 'xxxxx.com'
export const Fetch = ({
  url = '',
  data = {},
  header = { "content-type": "application/json" },
  method = 'GET'
}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: BaseUrl+ url,
      header: header,
      method: method,
      data: data,
      success: res => {
        // 成功时的处理
        if (res.status == 200) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail: err => {
        reject(err);
      }
    })
  })
}

对api进行统一的管理

import { Fetch } from './fetch.js';

export const PostMiniList = data => {
  return Fetch({
    url: '/api/getlist',
    data: data,
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    }
  })
}

export const GetMiniList = data => {
  return Fetch({
    url: '/api/getDetailByid',
    data: data
  })
}

你可能感兴趣的:(微信小程序)