axios拦截器

这篇博客详细介绍了如何在Vue项目中使用axios拦截器处理请求和响应。通过设置请求拦截器,将token添加到请求头中,确保每次请求都携带认证信息。响应拦截器用于处理后端返回的状态码,当接收到错误状态码如50008、50012、50014时,会弹出确认对话框提示用户重新登录,并清除token。此外,拦截器还提供了错误提示功能。
摘要由CSDN通过智能技术生成

axios拦截器的使用

//引入请求工具axios
import axios from 'axios'
// 该插件分装了 cookies的方法
import Cookies from 'js-cookie'
// 使用element-ui,在token失效时,给用户弹框提示。
import { Message, MessageBox } from 'element-ui'

//创建axios请求全局工具类实例,判断的所有的请求接口状态 
const service = axios.create({
  baseURL: 'localhost:8080',
  timeout: 5000
})
//请求拦截:主要用于 将token附带到请求头
service.interceptors.request.use(
  config => {
    // 如果存在 token 则附带在 http header 中
      config.headers['X-Token'] = Cookies.get('key名称') //需要和后端协商一致 token前面的key
      // console.log('config',config)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器:主要将返回的数据,先做出判断,识别当前是否请求超时等。
service.interceptors.response.use(
  response => {
    // console.log(response)
    const res = response.data   //res = {code:200,message:'成功',data:[]}
 
      if (res.code !== 200) {  //和后端协商的
       Message({
        message: res.message || 'Error',  //1.  5秒超时了 提示接口请求超时
        type: 'error',
        duration: 5 * 1000
      })
      //2. 判断 token 失效或者超时或token在异地登陆的场景
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // 如果 token 失效,则弹出确认对话框,用户点击后,清空 token 并返回登录页面
        MessageBox.confirm('您的token已失效,请重新登录', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload()//刷新当前页面
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // console.log(res)
      return res
    }
  },
  error => {
    Message({//出错提醒
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值