一.axios基本概念及语法

axios(阿克休斯) 官网 : axios中文网|axios API 中文文档 | axios

axios的全局基础路径:axios.defaults.baseURL=' url ' ;

axios是一个js框架,用于发送ajax请求(底层使用XMLHttpRequest)

二.axios推荐用法(两种写法)

第一种get和post写法)推荐

第一种对象写法{bookname:"三体",author:"大刘",publisher:"武汉出版社"}得到的是JSON类型:application/json

axios({
  url:'请求路径',
  method:'get',
  data: { 'post请求参数'},
  params: { 'get请求参数'}
 }).then(res=>{
    //成功回调
   console.log(res)
 })

(第二种get和post写法)

{ `bookname=三体&author=大刘&publisher=武汉出版社`}得到的是字符串类型:application/x-www-form-urlencoded:bookname

(三体&author=大刘&publisher=武汉出版社)

// post请求
axios
 .post('url',{post参数对象})
  //请求成功
 .then((res)=>{console.log(res)})
  //请求失败
 .catch(err=>{console.log(err)})

(第二种写法)get请求

axios.get('url', {params:{get参数对象}})
    //请求成功
    .then(res=>{console.log(res)})

三. get请求和post请求的区别

1.传参方式不同

(get在url后面拼接:请求行)(post在请求体传参)

2.大小限制不同

(get有大小显示,不同浏览器大小限制不同。一般2-5MB)

(post没有大小限制)

3.安全性不同

 (get参数直接暴露在url,不安全:一般查询类数据都是get)

 (post参数在请求体中更加安全:一般登录注册必须是post)

4.传输速度不同

   get传输速度快

   post传输速度慢

四.axios拦截器工作流程

 1. 浏览器发送请求服务器
     2. axios请求拦截器 : 添加ajax发送请求之前的操作
     3. 服务器 接收、处理、响应 请求
     4. 执行 响应拦截器 : 添加服务器响应之后的操作
     4. axios 接收响应(执行then方法)

<!-- 需求:点击然后请求拦截显示div盒子,到响应拦截隐藏div盒子 -->

<style>
    div {
      width: 100px;
      height: 100px;
      background-color: aqua;
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      margin: auto;
      display: none;
    }
  </style>
</head>

<body>
  <div></div>
  <!-- 需求:点击然后请求拦截显示div盒子,到响应拦截隐藏div盒子 -->

  <!-- 设置button按钮,点击之后就启动axios -->
  <button>点我启动ajax</button>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    //一般的我们把拦截器设置在前面

    // 添加请求拦截器
    axios.interceptors.request.use(function (config) {
      // 在发送请求之前做些什么
      //获取div盒子
      document.querySelector('div').style.display='block'
      return config;
    }, function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    });

    // 添加响应拦截器
    axios.interceptors.response.use(function (response) {
      // 对响应数据做点什么

      document.querySelector('div').style.display='none'
      return response;
    }, function (error) {
      // 对响应错误做点什么
      return Promise.reject(error);
    });

    document.querySelector('button').onclick = function () {
      axios({
        url: 'https://autumnfish.cn/api/cq',
        method: 'get',
        // params:{'query':'自然的纳兹伦'}
      }).then(res => console.log(res.data.list))
    }
  </script>
</body>

 五.编码和解码(返回值,需要接收)

//编码和解码:有返回值,需要接收
//编码:三组百分号为一个字
console.log(encodeURIComponent('红楼梦')) //%E7%BA%A2 %E6%A5%BC %E6%A2%A6'
//解码:
console.log(decodeURIComponent('%E7%BA%A2%E6%A5%BC%E6%A2%A6'))//'红楼梦'