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]))
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 用到的组件 1、通过CocoaPods安装 2、第三方类库安装 3、第三方服务 友盟社会化分享组件 友盟用户反馈 ...
    SunnyLeong阅读 14,709评论 1 180
  • 漫漫的长夜我享受孤独 无边无际的坠落把我吞噬 恰如黄昏的晚霞和破晓的晨光 弥散了整个天空 思念的寂寞 长蛇一般蜿蜒...
    上官飞鸿阅读 301评论 1 9
  • 大风姐,是儿时家里几个亲人叫起的花名。 因为网上已有人取网名为大风姐了,以示区别我就在前面加了个big。 弟弟说,...
    big大风姐阅读 257评论 0 0
  • 01 人的一生可以没看过《围城》,但是不能不懂“围城”。 钱钟书在《围城》里说:“结婚仿佛金漆的鸟笼,笼子外面的鸟...
    北国异乡人阅读 2,940评论 36 53