axios浅谈

axios处理http请求

axios使用起来非常方便,可以处理一下http请求

(function () {
  var axios = require('axios')
  var querystring = require('querystring')
  var instance = axios.create({
    // baseURL: 'https://test',
    headers: {
      'Content-Type': 'application/json'
    },
    timeout: 1000,
    withCredentials: false, // `withCredentials`指示是否跨站点访问控制请求
    responseType: 'json', // default
    // `headers`是要发送的自定义 headers
    // headers: {'X-Requested-With': 'XMLHttpRequest'},
    paramsSerializer: params => querystring.stringify(params),
    maxContentLength: 20000, // 定义允许的http响应内容的最大大小
    validateStatus: status => status >= 200 && status < 400,// 定义是否解析或拒绝给定的promise
    onUploadProgress: () => {},// `onUploadProgress`允许处理上传的进度事件
    onDownloadProgress: ()=> {}// `onDownloadProgress`允许处理下载的进度事件
  })
  
  instance.setConfig = function ({ baseURL, headers, timeout } = {}) {
    let dfs = instance.defaults
    headers && (dfs.headers = Object.assign(dfs.headers, headers))
    timeout && (dfs.timeout = timeout)
    baseURL && (dfs.baseURL = baseURL)
  }
  
  function get (url, params, { headers = {}, timeout, maxContentLength, onDownloadProgress } = {}) {
    let config = Object.assign({}, {
      url,
      params,
      headers: {
        'Content-Type': 'application/json; charset=utf-8'
      }
    }, arguments[2])
    return instance.request(config)
  }
  
  function post (url, data = {}, { params, headers = {}, timeout, maxContentLength, onUploadProgress, onDownloadProgress, urlencoded} = {}) {
    let config = Object.assign({}, arguments[2], {
      url,
      data: urlencoded ? querystring.stringify(data) : JSON.stringify(data), // queryString
      method: 'post',
      headers: Object.assign({}, {
        'Content-Type': urlencoded ? 'application/x-www-form-urlencoded' : 'application/json'
      }, headers)
    })
    return instance.request(config)
  }

  axios.interceptors.response.use(response => {
    return response.data
  }, error => {
    new Error({
      code: response.status,
      message: response.statusText
    })
  })
  
  window && (window.panfeel = {
    instance,
    get,
    post
  })
})()

获取随机数

在后端未给出接口之前,通过随机数可以mock一些数据

/**
 * @param {arg} : number or array
 *  number: return a int number with fixed length
 * for example:
 *   int([14, 18])  return a value [14, 18)
 *   int(10)  return a value,it‘s length is 10
 */
function int(arg) {
  if (!arg) return number()
  if (typeof arg === 'number') {
    return [...Array(arg)].reduce((accu, v, i) => {
      let tmp = i === 0 ? number({ range: [1, 10] }) : number()
      accu = accu * 10 + tmp
          return accu
    }, 0)
  } else if (arg instanceof Array && arg.length === 2) {
    return number({ range: arg })
  } else {
    console.error('int only accept a number or an range like [min, max] as params, pls check if you had pass a right param')
  }
}

/**
 * test [...Array(100)].forEach(i => console.log(float([1, 10], 3)) )
 * @param {*} range 取值范围
 * @param {*} decimal 保持小数后decimal位
 * for example:
 *   float()
 *   float([14, 18])
 *   float([14, 18], 10)
 */
function float(range = [0, 10], decimal) {
  return number({ range, decimal })
}

/**
 * int_list(10)
 * int_list(10, [10])
 * int_list(10, [[11, 90]])
 * @param {*} length array length
 * @param {*} config config of int
 */
function int_list(length, config) {
  return list(int, config || [], length)
}

/**
 * float_list(10)
 * float_list(10, [[100, 200]])
 * float_list(10, [[100, 200], 3])
 * @param {*} length array length
 * @param {*} config config of int
 */

function float_list(length, config) {
  return list(float, config || [], length)
}

function number (payload) {
  let { type = 'int', decimal = 0, range = [0, 10] } = payload || {}
  let m = range[1]
  let n = range[0]
  let power = Math.pow(10, decimal)
  let result = n + ( m - n) * Math.random()
  return Math.floor(result * power) / power
}


function list(fun, config, length) {
  return [...Array(length)].reduce((accu, v, i) => {
      accu.push(fun(...config))
      return accu
  }, [])
}


// test code here

console.log('\n---------test for use of int here---------: ')
console.log('int():', int())
console.log('int(10):', int(10))
console.log('int([14, 18]):', int([14, 18]))

console.log('\n---------test for use of int here---------: ')
console.log('int_list(10):', int_list(10))
console.log('int_list(10, [10]):', int_list(10, [10]))
console.log('int_list(10, [[11, 90]]):', int_list(10, [[11, 90]]))

console.log('\n---------test for use of float here---------: ')
console.log('float():', float())
console.log('float([14, 18]):', float([14, 18]))
console.log('float([14, 18], 10):', float([14, 18], 10))

console.log('\n---------test for use of float here---------: ')
console.log('float_list(10):', float_list(10))
console.log('float_list(10, [[100, 200]]):', float_list(10, [[100, 200]]))
console.log('float_list(10, [[100, 200], 3]):', float_list(10, [[100, 200], 3]))
axios浅谈_第1张图片
image.png

你可能感兴趣的:(axios浅谈)