axios在mvc框架的二次封装

1.封装http.js
import axios from 'axios'

const successCode = 0
const instance = axios.create({
  baseURL: '/api',
  withCredentials: true, // 跨域类型时是否在请求中协带cookie
})

export default class HttpUtil {
  static get(url, params = {}) {
    return new Promise((resolve, reject) => {
      instance.get(url, { params }).then(({ data }) => {
        //根据后台配置回调参数进行封装
      }).catch((err) => {
        //异常处理
        reject({ err: JSON.stringify(err) })
      })
    })
  }

  static post(url, params = {}) {
    return new Promise((resolve, reject) => {
      instance.post(url, { data: params }).then(({ data }) => {

      }).catch((err) => {
        reject({ err: JSON.stringify(err) })
      })
    })
  }
}

2.项目的api统一封装
import $http from './http'
export const  getData =  (params) => {
   return $http.get('/api', params) 
}
3.在项目中使用
import {getData} from '../http/index'
async getList(){
   return await getData({
      index:1,
      like:7
  })
}

你可能感兴趣的:(axios在mvc框架的二次封装)