zoukankan      html  css  js  c++  java
  • vue axios拦截器介绍

    关于axios的拦截器是一个作用非常大,非常好用的东西。分为请求拦截器和响应拦截器两种。
    我一般把拦截器写在main.js里。

    1. 请求拦截器

    请求拦截器的作用是在请求发送前进行一些操作,例如在每个请求体里加上token,统一做了处理如果以后要改也非常容易。

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

    2. 响应拦截器

    响应拦截器的作用是在接收到响应后进行一些操作,例如在服务器返回登录状态失效,需要重新登录的时候,跳转到登录页。

    
    axios.interceptors.response.use(function (response) {
        // 在接收响应做些什么,例如跳转到登录页
        ......
        return response;
      }, function (error) {
        // 对响应错误做点什么
        return Promise.reject(error);
      });
    

    3. 移除拦截器

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

    4. 为axios实例添加拦截器

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

    拦截器真的非常重要非常好用~

    原文地址:https://segmentfault.com/a/1190000016980755

  • 相关阅读:
    2021年2月22
    2021年2月21
    2021年2月20
    2021年2月19
    动态添加titie属性
    根据内容改变文字颜色!
    自定义弹出层!
    来回切换图标以及文字
    20180831xlVBA_WorksheetsCosolidate
    20180830xlVBA_合并计算
  • 原文地址:https://www.cnblogs.com/qixidi/p/10124563.html
Copyright © 2011-2022 走看看