axios学习笔记

1.将axios挂载到Vue原型上,实现组件的直接使用

背景:Vue中多组件每次都需要

import axios from 'axios'

后才能使用axios发送请求,在项目入口main.js中可以采用将axios挂载到Vue原型上,这样组件(Vue的实例)就可以直接访问了

//main.js中引入一次,并挂载
import axios from 'axios'
Vue.prototype.$http = axios

//在其他组件中可以直接使用
this.$http(url地址,参数).then()....

2.配置axios请求地址的公共路径以简化代码

//在入口文件main.js中配置
axios.defaults.baseURL = '公共路径'

//在组件中使用时
axiso.('/后缀路径',参数).then()...

3.axios的请求拦截器与响应拦截器

背景:当每次请求数据都要设置请求头信息时,采用请求拦截器实现请求头设置以简化代码

axios.interceptors.request.use(function (config) {
  //    console.log('请求已经被拦截')
  console.log(config)
  if (!config.url.endsWith('/login')) {
    config.headers.Authorization = localStorage.getItem('token')
  }
  return config
})

响应拦截器(暂时还不太理解这个的用法)(当token信息验证失败,直接跳转到登录页)

axios.interceptors.response.use(function (response) {
  //    console.log('响应已经被拦截')
  console.log(response)
  if (response.data.meta.status === 401) {
    router.push('/login')
    localStorage.removeItem('token')
  }
  return response
})

 

posted @ 2019-10-12 22:01  Zhou_135  阅读(406)  评论(0编辑  收藏  举报