zoukankan      html  css  js  c++  java
  • axios统一拦截配置

    在vue项目中,和后台进行数据交互使用axios。要想统一处理所有的http请求和响应,就需要使用axios的拦截器。通过配置http response inteceptor 统一拦截后台的接口数据,针对异常的情况可以做统一拦截处理。

    项目背景:vue+vuex+elementUI进行开发

    axios详细说明手册:https://www.kancloud.cn/yunye/axios/234845

    1、安装axios

    npm install --save axios

    2、在src/utils目录下,新建一个fetch.js文件,用于专门写axios的统一拦截操作。(具体路径存放已经文件名自定义)

      在fetch.js文件中,引入axios、element-ui的部分元素、引入vuex中的store、另外在引入其他相关的方法,例如获取token的方法

    import axios from 'axios';
    import { Message, MessageBox } from 'element-ui';
    import store from '../store';
    import { getToken } from 'utils/auth';
    // 创建axios实例
    const service = axios.create({
      // baseURL: process.env.BASE_API, // api的base_url
      timeout: 60000 // 请求超时时间,1分钟
    });
    

    // request拦截器 service.interceptors.request.use(config => { // Do something before request is sent if (store.getters.token) { config.headers['Authorization'] = getToken(); // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改 } return config; }, error => { Promise.reject(error); }) // respone拦截器 service.interceptors.response.use( response => { /** * 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页 * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中 */ const res = response.data; if (response.status === 401 || res.status === 40101) { MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', { confirmButtonText: '重新登录', cancelButtonText: '取消', cancelButtonClass: 'calBtnClass', type: 'warning' }).then(() => { store.dispatch('FedLogOut').then(() => { location.reload(); // 为了重新实例化vue-router对象 避免bug }); }) return Promise.reject('error'); } if (res.status === 40001) { Message({ message: '账户或密码错误!', type: 'warning' }); return Promise.reject('error'); } if (response.status !== 200 && res.status !== 200) { //此处并不能拦截全部异常情况,因为res是后台接口返回的数据,有一些由于不规范,没有带status属性,导致没有被拦截 Message({ message: res.message, type: 'error', duration: 6 * 1000 }); } else { //只有成功后,才可以进行操作 return response.data; } }, error => { Message({ message: error.message, type: 'error', duration: 6 * 1000 }); return Promise.reject(error); } ); export default service;

    以上代码,是一个完整的axios统一拦截配置处理。

    额外话:

    在学习axios的时候,对于defaults是很迷惑,有一些写法是axios.defaults.XXX。在了解以后,才知道axios的执行顺序是:默认值,实例默认值,参数设置值

    //设置默认值,设置默认超时时间为6000ms
    axios.defaults.timeout="6000"
    
    //创建实例,设置默认超时时间为8000ms
    const instance = axios.create();
    instance.defaults.timeout= 8000
    
    //请求,设置具体请求超时时间
    instance.get('/url',{
        timeout:1000*10
    })

    3、fetch.js配置完成以后,在调用请求的文件引入该文件即可

      例如:本人习惯的写法是把所有的请求方法写到一个js文件中,页面需要调用的时候,在import该文件。

      例如,在src/login.js文件中,存放和登录有关的全部请求方法,并在改文件中引入fetch.js

    import fetch from 'utils/fetch';
    
    //修改密码
    export function editPwsFun(obj,timeout) {
      return fetch({
        url: '/api/admin/user/current/updatePassword',
        method: 'post',
        data: obj,
    timeout }) }
    //查询当前登录用户信息 export function getCurUserInfo() { return fetch({ url: '/api/admin/user/current/user', method: 'get', }); } //修改当前用户信息 export function editCurUInfo(obj) { return fetch({ url: '/api/admin/user/current/updateUser', method: 'post', data: obj }) } // 执行登录 export function loginByEmail(username, password) { const data = { username, password}; return fetch({ url: '/api/auth/jwt/token', method: 'post', data }); } // logout注销 export function logout(token) { return fetch({ url: '/api/auth/jwt/invalid', method: 'post', params: { token } }); } // 获取用户信息 export function getInfo(token) { return fetch({ url: '/api/admin/user/front/info', method: 'get', params: { token } }); }

    4、接口文件完成以后,在vue文件中直接引入,并调用该方法即可。

    <script>
      import {editPwsFun, editCurUInfo, getCurUserInfo } from '../../api/login';
      export default {
         methods: {
             updateUserInfo() {
                getCurUserInfo().then(resopnse=> {
                  if (resopnse.status==200) {
                    this.formUInfo=resopnse.data;
                    this.dialogUInfoVisible = true;
                  } else {
                    this.dialogUInfoVisible=false;
                }
              })
          }
        }
      }
    </script>        
  • 相关阅读:
    Explicitly configure spring.jpa.open-in-view to disable this warning
    [LeetCode] 982. Triples with Bitwise AND Equal To Zero 按位与为零的三元组
    [LeetCode] 981. Time Based Key-Value Store 基于时间的键值存储
    [LeetCode] 980. Unique Paths III 不同的路径之三
    [LeetCode] 979. Distribute Coins in Binary Tree 在二叉树中分配硬币
    [LeetCode] 978. Longest Turbulent Subarray 最长湍流子数组
    [LeetCode] 976. Largest Perimeter Triangle 最大周长的三角形
    [LeetCode] 977. Squares of a Sorted Array 有序数组的平方值
    [LeetCode] 975. Odd Even Jump 奇偶跳跃
    [LeetCode] 974. Subarray Sums Divisible by K 子数组数字之和可被K整除
  • 原文地址:https://www.cnblogs.com/luoxuemei/p/9896627.html
Copyright © 2011-2022 走看看