Vue全家桶之axios(发送异步请求 && 拦截器)

axios的基本使用

一、axios 简介

axios异步请求技术

axios 简介:axios是一个基于 promise 的 http 库,可以用在 浏览器 和 node.js 中

1、axios 前端异步请求库 类似于jquery ajax 技术

ajax 用来在页面发布异步请求到后端服务,并将后端服务响应的数据渲染到页面上

jquery 推荐使用 ajax 技术 vue 里面并不推荐使用 jquery 框架了 vue 中推荐使用 axios 异步请求库

axios 总结: 在前端页面上发布一个异步请求 ,请求之后页面不动 ,响应回来刷新页面局部

官方网站 : 易用 ,简洁且高效的http库 =======》》》》发送http异步请求库

特性:

  1. 从浏览器中创建 XMLHttpReques

  2. 支持 Promise API

  3. 客户端支持防止CSRF

  4. 提供了一些并发请求的接口(重要,方便了很多的操作)

  5. 从 node.js 创建 http 请求

  6. 拦截请求和响应

  7. 转换请求和响应数据

  8. 取消请求

  9. 自动转换JSON数据

二、axios 基本使用

【1】下载核心js 文件

https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

【2】在页面中引入axios核心js

<script src = "js/axios.min.js"></script>

【3】发送异步请求

1、get ()方式

   axios.get("https://autumnfish.cn/api/joke/list?num=10")
        .then(function(response) {           //代表请求成功之后处理
            console.log(response.data);
        })
         .catch(function(err) {                   //代表请求失败之后处理
            console.log(err);
        })

2、 post() 方式的请求

    axios.post("https://autumnfish.cn/api/user/reg", {
            username: "盐焗西兰花"
        })
        .then(function(response) {
            console.log(response);
        })
        .catch(function(err) {
            console.log(err);
        })

3、 put( ) 方式的请求

axios.put().then(function(response){ }).catch(function(err){});

4、patch( )方式的请求

axios.patch().then(function(response){ }).catch(function(err){});

5、delete( )方式的请求

axios.patch("url?id=21").then(function(response){ }).catch(function(err){});

【4】创建axios的默认实例发送请求

   
//创建axios的默认配置对象
    var instance = axios.create({
        baseURL: "https://autumnfish.cn/api/joke/", //将自动加载到URL前面,除非URL是一个绝对的URL
        timeout: 5000,           //默认加载5秒,若未加载成功,终止请求
    })

//发送 get 方式请求
    instance.get("/list?num=3")
        .then(function(response) {
            console.log(response.data)
        }).catch(function(err) {
            console.log(err)
        })

【5】axios中的拦截器

1、作用: 将 axios 中共有的参数,响应公共处理交给拦截器处理,减少axios发送请求时的代码冗余

2、拦截器类型:

a、请求拦截器

b、响应拦截器

3、拦截器(interceptors)的使用

a、可以给原始的axios加拦截器

b、可以给创建出来的axios配置对象加拦截器

在请求或响应被 then 或 catch 处理前拦截它们。


// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });



// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });

如果你稍后需要移除拦截器,可以这样:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

可以给自定义的 axios 实例添加拦截器。

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

猜你喜欢

转载自blog.csdn.net/m0_57002951/article/details/123717677
今日推荐