axios封装

vue项目
引入axios
import axios from 'axios'

创建axios

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, 
    timeout: 5000,
    headers: {
      "Content-Type": "application/json;charset=utf-8"
  })

请求拦截

service.interceptors.request.use(
 config => {
   config.headers = config.headers || {}
   if (localStorage.getItem('token')) {
     config.headers.token= localStorage.getItem('token') || ''
   }
   return config
 },
 error => {
   console.log(error)
   return Promise.reject(error)
 }
)

响应拦截

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 200) {
       if (error.response.status == 401) {
          localStorage.removeItem("token");
          setTimeout(()=> {
            window.location.reload()
          }, 500)
          return Promise.reject(res.messge)
        }
        return Promise.reject(error.response.data || 'Error')
    } else {
      return res
    }
  },
  error => {
    // elementui 组件
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

posted @ 2022-10-12 14:48  像鱼灵活的猫  阅读(82)  评论(0编辑  收藏  举报