小程序request封装

  • request.js封装

const request = options => {
  return new Promise((resolve, reject) => {
    const { data, method } = options;
    if (data && method !== 'get') {
      options.data = JSON.stringify(data)
    }
    wx.request ({
      header: {'Content-text':'application/json'},
      ...options,
      success: function (res) {
        //请根据需求自行判断状态码,这里只判断statusCode==200
        if (res.statusCode==200) {
          let data = res.data
          resolce(data)
        }else{
          reject(res)
        }
      },
      fail: function (res) {
        console.error('接口没走通',res)
      }
    })
  })
}
export default request

api.js:接口的使用

import request from '../utils/request'
let app_url = getApp().appurl 
//method=='get'
export function xxx1 (header,roomID) {
  return request({
    url: `${app_url}/calendar?roomId=${roomID}`,
    method: 'get',
    header
  })
}
//method=='post'
export function xxx2 (header, data) {
  return request({
    url: `${app_url}/saveRoomShare`,
    method: 'post',
    header,
    data
  })
}

接口调用

import { xxx1,xxx2 } from '../../api.js'
//直接调用即可
......

你可能感兴趣的:(小程序request封装)