AlexZ33 / lessions

自己练习的各种demo和课程
12 stars 2 forks source link

axios封装问题 #25

Open AlexZ33 opened 5 years ago

AlexZ33 commented 5 years ago

关于axios的封装有很多风格,这里提供一些简单封装


...
const _do = (method) => (url, params) => {
  let data = null
  if (method === 'get') {
    if (params && typeof params === 'object' && Object.keys(params).length > 0) {
      url = url + '?' + Object.keys(params).map((key) => {
        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
      }).join('&')
    }
  } else {
    if (params && typeof params === 'object') {
      data = params || null
    }
  }

  return axios({
    method,
    url,
    data,
    timeout: TIMEOUT
  })
    .then(response => {
      return response.data
    })
    .catch(err => {
      return Promise.reject(err)
    })
}
...

const GET = _do('get')
const DELETE = _do('delete')
const POST = _do('post')
const PUT = _do('put')
...

export {
  GET,
  POST,
  PUT,
  DELETE
}
AlexZ33 commented 4 years ago

关于Axios的GET与DELETE用法注意事项