axios 请求方法封装

import $axios from '../axios-mall'
import { queryStringify, filterEmpty } from '../utils'

/**
 * ajax get
 * @param url
 * @param config
 * @returns {AxiosPromise<any>}
 */
export const get = (url, params = {}, config = {}) => {
  const options = Object.assign({}, { params: filterEmpty(params, [null, undefined], false) }, config)
  return $axios.get(url, options)
}

/**
 * ajax post from-data
 * @param url
 * @param data
 * @param config
 */
export const post = (url, data = {}, config = {}) => {
  // query序列化
  let query = queryStringify(filterEmpty(data, [null, undefined], false))
  config['Content-Type'] = 'application/x-www-form-urlencoded'
  return $axios.post(url, query, config)
}

/**
 * ajax post application/json
 * @param url
 * @param data
 * @param config
 */
export const postJson = (url, data = {}, config = {}) => {
  config['Content-Type'] = 'application/json;charset=UTF-8'
  config.timeout = 1000 * 120
  return $axios.post(url, filterEmpty(data, [null, undefined], false), config)
}

/**
 * post上传文件
 * @param url
 * @param data
 * @param config cnfig[onUploadProgress]方法可以监听文件上传进度
 */
export const postFile = (url, data = {}, config = {}) => {
  config['Content-Type'] = 'multipart/form-data;charset=UTF-8'
  config.timeout = 1000 * 60 * 30
  const temp = filterEmpty(data, [null, undefined], false)
  const formatData = new FormData()
  for (const key in temp) {
    formatData.append(key, temp[key])
  }
  return $axios.post(url, formatData, config)
}

export default {
  get,
  post,
  postJson,
  postFile
}

  

posted @ 2023-06-29 17:28  wangwht  阅读(20)  评论(0编辑  收藏  举报