• Axios


    Axios

    Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

    文档:https://axios.nodejs.cn/

    Axios特性

    • 从浏览器中创建 XMLHttpRequests
    • 从 node.js 创建 http 请求
    • 支持 Promise API
    • 拦截请求和响应
    • 转换请求数据和响应数据
    • 取消请求
    • 自动转换 JSON 数据
    • 客户端支持防止 CSRF

    安装

    使用 npm:

    $ npm install axios
    
    • 1

    使用 yarn:

    $ yarn add axios
    
    • 1

    使用方法

    发送一个 GET 请求:

    axios.get('/user', {
        params: {
          ID: 12345
        }
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      })
      .finally(function () {
        // always executed
      });  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    Axios 也支持 POST 请求:

    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    发送表单数据:

    const {data} = await axios.post('https://httpbin.org/post', {
        firstName: 'Fred',
        lastName: 'Flintstone',
        orders: [1, 2, 3],
        photo: document.querySelector('#fileInput').files
      }, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    Axios 实例

    我们可以使用自定义配置创建一个新的 axios 实例。

    const instance = axios.create({
      baseURL: 'https://some-domain.com/api/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'foobar'}
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5

    拦截器

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

    // Add a request interceptor
    axios.interceptors.request.use(function (config) {
        // Do something before request is sent
        return config;
      }, function (error) {
        // Do something with request error
        return Promise.reject(error);
      });
    
    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        return response;
      }, function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    取消请求

    Axios 允许创建自定义的实例,配置默认的请求行为:
    javascript
    // Create an instance with the default settings
    const instance = axios.create({
      baseURL: 'https://api.example.com'
    });
    
    // Alter defaults after instance has been created
    instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
    
    // Send a GET request
    instance.get('/user/12345')
      .then(function(response){
        console.log(response.data);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    响应结构

    响应的数据结构包括以下几个重要部分:

    axios.get('/user/12345')
      .then(function(response) {
        console.log(response.data);
        console.log(response.status);
        console.log(response.statusText);
        console.log(response.headers);
        console.log(response.config);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    错误处理

    处理请求错误时,Axios 会将错误封装在一个统一的对象中:

    axios.get('/user/12345')
      .catch(function (error) {
        if (error.response) {
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        } else if (error.request) {
          // The request was made but no response was received
          console.log(error.request);
        } else {
          // Something happened in setting up the request that triggered an Error
          console.log('Error', error.message);
        }
        console.log(error.config);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在Vue中封装Axios

    import axios from "axios";
    import { ElMessage } from "element-plus";
    
    const baseURL = "http://127.0.0.1:8000";
    const instance = axios.create({
      baseURL: baseURL,
      timeout: 5000,
    });
    
    instance.interceptors.request.use(
      (config) => {
        // 添加用户token
        return config;
      },
      (e) => Promise.reject(e)
    );
    
    // 添加响应拦截器
    instance.interceptors.response.use(
      function (response) {
        // 2xx 范围内的状态码都会触发该函数。
        // 对响应数据做点什么
        return response;
      },
      async function async(error) {
        // 超出 2xx 范围的状态码都会触发该函数。
        // 对响应错误做点什么
        if (error.response.status === 401) {
          // 可验证用户是否登录
          ElMessage.error("登录状态失效,请重新登录");
        }
        ElMessage.error(
          error.response.data.detail || error.response.data.error || "服务异常"
        );
        return Promise.reject(error);
      }
    );
    
    export default instance;
    export { baseURL };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
  • 相关阅读:
    【数字信号调制】基于PCM编码和QAM调制系统附matlab代码
    【NET 7.0、OpenGL ES】使用Silk.NET渲染MMD,并实时进行物理模拟。
    Java——Map,Set
    【stm32】DAC输出三角波锯齿波
    ToBeWritten之评估数据质量
    基于Java web的电动车销售平台 毕业设计-附源码201524
    Discourse 的无效附件清理
    OpenFeign的实现原理(附Feign和OpenFeign的区别)
    Eureka介绍与使用
    LeetCode 235 二叉搜索树的最近公共祖先 701 二叉搜索树中的插入操作 450删除二叉搜索树中的节点
  • 原文地址:https://blog.csdn.net/weixin_74144099/article/details/138160157