Vue下的axios封装

一、在utils文件下新建request.js,对axios重新封装

import axios from 'axios'
import { ElMessage } from 'element-plus'

const TOKEN_INVALID = 'Token认证失败,请重新登录'
const NETWORK_ERROR = '网络请求异常,请稍后重试'

// 创建axios实例
let service = axios.create({
  //   baseURL: process.env.BASE_URL || 'prod',
  baseURL: 'https://www.fastmock.site/mock/d9e148087bcae80d40622e393a3da21b/api',
  timeout: 8000
})

// request拦截器
service.interceptors.request.use(
  req => {
    const header = req.headers
    if (!header.Authorization) header.Authorization = 'test token'
    return req
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  res => {
    const { data, statusText } = res
    if (res.status === 200) {
      return data
    } else if (res.status === 40001) {
      ElMessage.error(statusText)
    }
    return Promise.reject(TOKEN_INVALID)
  },
  error => {
    ElMessage.error(error || NETWORK_ERROR)
    return Promise.reject(error || NETWORK_ERROR)
  }
)

export default service

二、实例使用

import { onMounted } from 'vue';
import service from "@/utils/request";
export default {
  name: 'Home',
  components: {
  },
  setup() {
   onMounted(() => {
      service.post('/user/login', {
        username: 'admin',
        password: '123456'
      }).then(res => {
        console.log(res)
      })
    })
    return {
    }
  }
}

你可能感兴趣的:(Vue下的axios封装)