小程序请求浅封装

request.js

import wepy from 'wepy'
// 接口前缀
import { prefix } from '@/config.js'


function checkStatus(response) {
  if (response.statusCode >= 200 && response.statusCode < 300) return response
  const error = new Error(response.errMsg)
  error.response = response
  throw error
}

function valideData(obj) {
  const { data } = obj
  const { code, message, data: resData } = data
  if (Number(code) === 1) {
    return resData
  } else {
    throw message
  }
}

function catchErr(err) {
  const { errMsg } = err
  wx.showToast({
    title: errMsg,
    icon: 'none',
    duration: 2000,
  })
}

export default function request(url, options) {
  return wepy.request({
    url: `${prefix}${url}`,
    ...options
  }).then(checkStatus)
    .then(valideData)
    .catch(catchErr)

}


base.js

import qs from 'qs'
import request from './request.js'
// 对get、post、delete、put四种方法做简单封装
// 后面所有的请求都是调用这几个方法


export function get({ path, params }) {
  const pStr = params ? `?${qs.stringify({...params, time: new Date().getTime()})}` : ''
  return request(`${path}${pStr}`, {
    method: 'GET',
    header: {
      'Content-Type': 'application/json',
      Accept: 'application/json'
    }
  })
}


export function post({ path, params }) {
  return request(path, {
    method: 'POST',
    header: {
      'Content-Type': 'application/json',
      Accept: 'application/json'
    },
    data: JSON.stringify(params)
  })
}


export function remove({ path, params }) {
  return request(path, {
    method: 'DELETE',
    header: {
      'Content-Type': 'application/json',
      Accept: 'application/json'
    },
    data: JSON.stringify(params)
  })
}


export function put({ path, params }) {
  return request(path, {
    method: 'PUT',
    header: {
      'Content-Type': 'application/json',
      Accept: 'application/json'
    },
    data: JSON.stringify(params)
  })
}

你可能感兴趣的:(javascript,小程序)