Axios全方位解析+运用

62 阅读2分钟

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous" />
  <title>Axios全方位解析+运用</title>
</head>

<body>
  <div class="container my-5">
    <div class="text-center">
      <h1 class="display-4 text-center mb-3">Axios全方位运用</h1>
      <button class="btn btn-primary my-3" id="get">GET</button>
      <button class="btn btn-info" id="post">POST</button>
      <button class="btn btn-warning" id="update">PUT/PATCH</button>
      <button class="btn btn-danger" id="delete">DELETE</button>
      <button class="btn btn-secondary" id="sim">批量请求</button>
      <button class="btn btn-secondary" id="headers">请求头</button>
      <button class="btn btn-secondary" id="transform">Transform</button>
      <button class="btn btn-secondary" id="error">Error处理</button>
      <button class="btn btn-secondary" id="cancel">取消请求</button>
    </div>
  </div>

  <!-- 引入axios: CDN方式 或 下载axios.min.js至本地 -->
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <!-- 引入脚本 -->
  <script src="start.js"></script>

</body>

</html>

start.js

// GET 请求
function getTodos() {
  // 方式1
  // axios({
  //   method: 'get',
  //   url: 'http://jsonplaceholder.typicode.com/todos',
  //   params: {
  //     _limit: 5 // 请求5条
  //   }
  // })
  //   .then(res => { console.log('get', res) })
  //   .catch(err => console.log(err))
  // 方式2
  axios('http://jsonplaceholder.typicode.com/todos?_limit=5', {
    timeout: 5000 // 超过50毫秒 就不在发送请求了
  })
    .then(res => { console.log('get', res) })
    .catch(err => console.log(err))
}

// post 请求
function addTodos() {
  axios.post('http://jsonplaceholder.typicode.com/todos', {
    title: 'post测试',
    complete: false
  })
    .then(res => console.log('post', res))
    .catch(err => console.log(err))
}

// put/patch 请求
function updateTodo() {
  axios.patch('http://jsonplaceholder.typicode.com/todos/1', {
    title: 'patch测试',
    complete: true
  })
    .then(res => console.log('patch', res))
    .catch(err => console.log(err))
}

// delete 请求
function removeTodo() {
  axios.delete('http://jsonplaceholder.typicode.com/todos/1')
    .then(res => console.log('delete', res))
    .catch(err => console.log(err))
}

// 批量请求
function getData() {
  axios.all([
    axios.get('http://jsonplaceholder.typicode.com/todos?_limit=5'),
    axios.get('http://jsonplaceholder.typicode.com/posts?_limit=5'),
  ])
    // .then(res=>console.log(res[1]))
    .then(axios.spread((todos, posts) => console.log('批量[1]', posts)))
    .catch(err => console.log(err))
}

// 自定义请求头
function customHeaders() {
  const config = {
    headers: {
      "Content-Type": "application/json",
      Authorization: 'sometoken0002' // Authorization post+put+delete请求方式  response.config.headers.可查看
    }
  }

  axios.post('http://jsonplaceholder.typicode.com/todos', {
    title: '自定义请求头测试',
    complete: true
  }, config)
    .then(res => console.log('自定义请求头', res))
    .catch(err => console.log(err))
}



// 对请求和响应 进行转换
function transformResponse() {
  const options = {
    method: 'post',
    url: "http://jsonplaceholder.typicode.com/todos",
    data: { title: 'hello world' },
    transformResponse: axios.defaults.transformResponse.concat(data => {
      data.title = data.title.toUpperCase();
      return data
    })
  }
  axios(options).then(res => console.log('对请求头的title值进行转换', res))

}

// error 处理
function errorHandle() {
  axios('http://jsonplaceholder.typicode.com/todoss') // 错误的地址
    .then(res => { console.log('error', res) })
    .catch(err => {
      // error3情况-01 请求已发起,有响应
      if (err.response) {
        const { data, status, headers } = err.response
        console.log('err处理 data, status, headers', data, status, headers)
        if (status == 404) {
          alert('客户端请求出现问题!')
        } else if (status >= 500) {
          alert('服务端接口出现问题!')
        }
      } else if (err.request) {  // error3情况-02:请求已发起,没有响应(需后端配合)
        console.log(err.request)
      } else {
        console.log(err.message) // error3情况-03:请求已发起,没有响应(需后端配合)
      }
    })
}

// 设置token信息携带 给服务端(服务端用来校验)
// 查看token信息 response.config.headers.X-Auth-Token
// axios.defaults.headers.common["X-Auth-Token"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"


// 取消请求 处理【根据某种条件的成立,取消当前请求 】
// jwt.io  地址可生成真实的token
function cancelToken() {
  const source = axios.CancelToken.source(); // 生成取消token对象,实际是promise
  axios('http://jsonplaceholder.typicode.com/todos', {
    cancelToken: source.token
  })
    .then(res => { console.log('get', res) })
    .catch(thrown => {
      if (axios.isCancel(thrown)) {
        console.log('request canceled', thrown.message)
      }
    })

  // 根据某种条件的成立,取消当前请求 
  // 【触发取消请求】:异步请求会后执行,所以会先触发 请求取消,上面的异步请求不会走.then(),会走.catch()
  if (true) {
    source.cancel('请求取消')  // 此携带的实参 === thrown.message
  }
}


// 请求拦截 (每次请求前都会触发)
axios.interceptors.request.use(
  config => {
    console.log(`${config.method.toUpperCase()} 请求地址:${config.url} at ${new Date().getTime()}`);
    return config;
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截


// 实例化Axios 开始
const axiosInstance = axios.create({
  baseURL: 'http://jsonplaceholder.typicode.com' // 指定请求根域名
});
// axiosInstance.get('/comments').then(res => console.log('实例化Axios的get请求', res)) // 自调用了1次,不用触发事件
// 实例化Axios 结束



// 事件监听
document.getElementById('get').addEventListener('click', getTodos);
document.getElementById('post').addEventListener('click', addTodos);
document.getElementById('update').addEventListener('click', updateTodo);
document.getElementById('delete').addEventListener('click', removeTodo);
document.getElementById('sim').addEventListener('click', getData);
document.getElementById('headers').addEventListener('click', customHeaders);
document.getElementById('transform').addEventListener('click', transformResponse);
document.getElementById('error').addEventListener('error', errorHandle);
document.getElementById('cancel').addEventListener('click', cancelToken);