zoukankan      html  css  js  c++  java
  • vue中 aixos 常用配置 aixos拦截器 interceptors的使用

                                        axios的配置   公共路径配置    拦截器的使用

     1 //这个文件是根组件 new Vue,所有所需的模块和对象都要在new Vue之前配置好
     2 
     3 import Vue from 'vue'
     4 import App from './App.vue'
     5 import router from './router'
     6 import store from './store'
     7 import ElementUI from 'element-ui'
     8 import 'element-ui/lib/theme-chalk/index.css'
     9 
    10 //手动引入
    11 import axios from 'axios' //引入axios文件  
    12 //将axios添加到vue的原型对象中,
    13 // 实例对象可以直接使用原型对象中的属性和方法 
    14 //所有的组件都是vue的实例,所有组件都可通过 this.$http使用axios 
    15 // 说明:只要是像axios这样得第三方库(与vue没有任何关系),都应该通过这种方式统一去导入
    16 Vue.prototype.$http=axios  //以后再组件中 使用 this.$http就可使用axios
    17 
    18 //配置公共路径
    19 // 配置好公共路径后,每次使用axios发送请求,只需要写当前接口的路径(比如'/product')
    20 // axios在发送请求之前,会将baseUrl + '/product' 得到完整的路径,才会发送请求
    21 axios.defaults.baseURL='http://localhost:8888/api/private/v1'
    22 
    23 // axios.defaults.withCredentials=true //让axios的请求携带验证信息到服务端(钥匙)
    24 
    25 
    26 
    27 // 只要配置了拦截器,那么所有的请求都会走拦截器
    28 // 因此,可以在拦截器中统一处理headers(处理:除了登录接口以外的所以接口,都需要将token传递给服务器)
    29 // 请求拦截器(Add a request interceptor )
    30 axios.interceptors.request.use(
    31   function (config) {
    32     //在请求发送之前做一些事情
    33     // endsWith 字符串的方法,用来判断是不是以参数结尾的,如果是返回值为true
    34     if(!config.url.endsWith('/login')){// 判断如果是登录接口,就不需要添加 Authorization 请求头
    35       config.headers['Authorization']=localStorage.getItem('token')  //将token设置在请求头,传递给服务器接口,这样才能正确的调用这个接口
    36     }
    37        return config;
    38 }, 
    39 );
    40 
    41 //   响应拦截器(Add a response interceptor)
    42 axios.interceptors.response.use(
    43   function (response) {
    44     //在获取到响应的时候做一些事情, 
    45     if(response.data.meta.status===401){//只要token失效,就跳转回登录页面
    46       //因为现在不是在组件中,因此无法通过this.$router来访问到路由实例
    47       // 但是可以直接通过 上面导入的路由模块中的 router来访问到路由
    48         router.push('/login') //跳转到登录页
    49         localStorage.removeItem('token')
    50     }
    51     console.log( response )
    52        return response;
    53 },
    54 );
    55 
    56 
    57 
    58 //导入全局css样式  @表示src
    59 import '@/assets/index.css'
    60 
    61 Vue.config.productionTip = false
    62 
    63 Vue.use(ElementUI)
    64 
    65 new Vue({
    66   router,
    67   store,
    68   render: h => h(App)
    69 }).$mount('#app')
  • 相关阅读:
    LA 3882
    Codeforces 161D
    spoj PARTIT
    uva 10496 Collecting Beepers
    uva 10130 SuperSale
    spoj 3885
    NWERC 2012 Problem I Idol
    NWERC 2012 Problem E Edge Case
    【USACO 1.3.2】修理牛棚
    【USACO 1.3.1】混合牛奶
  • 原文地址:https://www.cnblogs.com/javascript9527/p/11373506.html
Copyright © 2011-2022 走看看