展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

axios入门(二): 拦截器

  • 代码案例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拦截器</title>
</head>
<body>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
    <script>
      // 添加两个请求拦截器(回调函数)
      axios.interceptors.request.use(
        config => {
          console.log('request interceptor1 onResolved()') // -----------2
          return config
        },
        error => {
          console.log('request interceptor1 onRejected()')
          return Promise.reject(error)
        }
      )

      axios.interceptors.request.use(
        config => {
          console.log('request interceptor2 onResolved()') // -----------1
          return config
        },
        error => {
          console.log('request interceptor2 onRejected()')
          return Promise.reject(error)
        }
      )

      // 添加两个响应拦截器
      axios.interceptors.response.use(
        resopnse => {
          console.log('response interceptor1 onResolved()') // -----------3
          return resopnse
        },
        error => {
          console.log('response interceptor1 onRejected()')
          return Promise.reject(error)
        }
      )

      axios.interceptors.response.use(
        resopnse => {
          console.log('response interceptor2 onResolved()') // -----------4
          return resopnse
        },
        error => {
          console.log('response interceptor2 onRejected()')
          return Promise.reject(error)
        }
      )

      axios.get('http://localhost:3000/posts')
        .then(response => {
          console.log('data', response.data) //data Array(4) -------------5
        })
        .catch(error => {
          cosole.log('error', error.message)
        })

      // 多个拦截器执行顺序:
      // request interceptor2 onResolved()
      // request interceptor1 onResolved()
      // response interceptor1 onResolved()
      // response interceptor2 onResolved()
      // data Array(4)
    </script>
</body>
</html>
posted @ 2022-09-08 13:28  DogLeftover  阅读(46)  评论(0编辑  收藏  举报