1.基本写法

第一种写法


axios.get('/data.json').then((res)=>{
      console.log(res)
    })
    

第二种


axios({
  method:'get',
  url:'/data.json'
}).then((res)=>{
     console.log(res)
})

当要携带参数

第一种


axios.get('/data.json',{
      params:{
        id:12
      }
    }).then((res)=>{
      console.log(res)
    })
    

第二种


axios({
  method:'get',
  url:'/data.json',
  params:{
    id:12
  }
}).then((res)=>{
     console.log(res)
})

给后端发送数据

假设发送的数据为 senddata={id:1,name:"张三"}

第一种


axios.post('/post',senddata).then((res)=>{
  console.log(res)
})

第二种


axios({
  method:'post',
  url:'/post',
  data:senddata
}).then(()=>{
  console.log(res)
})

配置请求超时时间

全局配置

axios.defaults.timeout = 1000 //全局配置请求时长1s

第一种


axios.post(url, params, {timeout: 1000})
    .then(res => {
        console.log(res);
    })
    .catch(err=> {
        console.log(err);
    })
}) 

第二种


axios({
  method:'post',
  url:'/post',
  timeout: 50000
}).then(()=>{
  console.log(res)
})

axios.create

可以把一些反复出现的配置写在这里面

基本语法


const instance = axios.create({
   baseURL:"http://localhost:3000"
})

// 使用instance发请求
instance({
    url:"/posts"
}).then(()=>{
  console.log(res)
})



 

axios.interceptors.request.use(拦截器)

请求拦截器


axios.interceptors.request.use(
   config=>{
     //在发送请求前做些什么
     return config
   },
   err=>{
     // 在请求错误的时候做些什么(此处错误,请求没有到后端)
     return Promise.reject(err)//这里返回一个promise对象
   }
 )

响应拦截器


axios.interceptors.request.use(
   config=>{
     //在发送请求前做些什么
     return config
   },
   err=>{
     // 在请求错误的时候做些什么(此处错误,请求没有到后端)
     return Promise.reject(err)//这里返回一个promise对象
   }
 )
 

axios-retry

axios-retry可以让一个失败的网络请求再次自动发送n(自定义)次数

安装

npm install axios-retry

引入

import axiosRetry from 'axios-retry';

使用

axiosRetry(axios, { retries: 3 });

在这里插入图片描述
在这里插入图片描述

图片来自:https://juejin.cn/post/7053471988752318472

取消请求


const CancelToken = axios.CancelToken;

axios({
      url: 'http://127.0.0.1:8005/server1',
      cancelToken: new CancelToken(function executor(c) {
        // executor 函数接收一个 cancel 函数作为参数
        cancel = c
      })
    })
    
 //点击xxx取消请求
xxx.onclick=function(){
  cancel()
}    

多次发起请求取消上一次请求

<!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>Document</title>
</head>

<body>
  <button>点我发送请求</button>
  <button>手动取消请求</button>
</body>

</html>
<script>
  const CancelToken = axios.CancelToken;
  var cancel;
  //点击按钮发送请求,多次点击取消上一次请求
  one.onclick = function () {
    if (typeof cancel === 'function') {
      cancel()
        //判断上一次请求是否是一个函数,如果是一个函数的话就取消上一次请求(axios把取消请求的函数封装在了cancel中,每次点击按钮就会把cancel封装成一个函数)如果请求执行完成或者请求错误就把cancel设置成不是一个函数
        (cancel = null)//判断如果上一次没执行完的话就取消他
    }
    axios({
      url: 'http://127.0.0.1:8005/server1',
      cancelToken: new CancelToken(function executor(c) {
        // executor 函数接收一个 cancel 函数作为参数
        cancel = c
      })
    })
      .then(function (a) {
        cancel = null
        //执行完成把cancel设置成不是一个函数 (cancel = null)
        console.log(a.data);
      })
      .catch(function (b) {
        if (axios.isCancel(b)) {
          //这句话的意思是如果是手动取消 axios是cancel axios是手动取消
          //这里需要判断错误类型,一种是自己手动取消的一种是请求完成但是出现了错误下次再点击的时候就会判断这个函数是不是函数
          //如果是自己手动取消的话这个请求没执行完让cancel是一个函数在下次点击的时候就会取消这个请求
          //如果是出现了错误那就让cancel不是一个函数,因为这个请求已经执行完事了,再次点击的时候就不用管他了
          console.log('手动取消');
        }
        else {
          cancel = null **//请求错误就把cancel设置成不是一个函数 (cancel = null)**
            console.log('发送失败');
        }
      })
  }
  //手动取消请求
  cancel.onclick = function () {
    if (typeof cancel === 'function') {//这句话的意思是如果cancel是一个函数
      cancel()
      //如果是一个函数的话就取消这次请求
      //也可能之没发送请求(没把cancel设置成一个函数)或者请求已经执行完成(上面已经把请求执行完成的cancel设置成不是一个函数)
    }
    else (
      alert('没有可取消的请求')
    )
  }

</script>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐