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`是要發(fā)送的自定義 headers
    // headers: {'X-Requested-With': 'XMLHttpRequest'},
    paramsSerializer: params => querystring.stringify(params),
    maxContentLength: 20000, // 定義允許的http響應(yīng)內(nèi)容的最大大小
    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
  })
})()

獲取隨機數(shù)

在后端未給出接口之前,通過隨機數(shù)可以mock一些數(shù)據(jù)

/**
 * @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 保持小數(shù)后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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,544評論 19 139
  • 用到的組件 1、通過CocoaPods安裝 2、第三方類庫安裝 3、第三方服務(wù) 友盟社會化分享組件 友盟用戶反饋 ...
    SunnyLeong閱讀 15,159評論 1 180
  • 漫漫的長夜我享受孤獨 無邊無際的墜落把我吞噬 恰如黃昏的晚霞和破曉的晨光 彌散了整個天空 思念的寂寞 長蛇一般蜿蜒...
    上官飛鴻閱讀 338評論 1 9
  • 大風(fēng)姐,是兒時家里幾個親人叫起的花名。 因為網(wǎng)上已有人取網(wǎng)名為大風(fēng)姐了,以示區(qū)別我就在前面加了個big。 弟弟說,...
    big大風(fēng)姐閱讀 309評論 0 0
  • 01 人的一生可以沒看過《圍城》,但是不能不懂“圍城”。 錢鐘書在《圍城》里說:“結(jié)婚仿佛金漆的鳥籠,籠子外面的鳥...
    北國異鄉(xiāng)人閱讀 3,050評論 36 53

友情鏈接更多精彩內(nèi)容