VUE3整合pinia存储和axios封装,添加环境变量,处理跨域

安装依赖

npm install axios
npm install pinia

创建一个员工存储实例src/store/staffStore.ts

import { defineStore } from 'pinia'
export const useStaffStore = defineStore('staff', {
  state: () => ({
    token: '',
    staff: null,
  }),
  actions: {
    setToken(token: string) {
      this.token = token
    },
    logOut() {
      this.token = ''
    },
  },
})

创建一个操作token的常用方法utils/auth.ts

const TokenKey = 'token'

export function getToken() {
  return localStorage.getItem(TokenKey)
}

export function setToken(token: string) {
  return localStorage.setItem(TokenKey, token)
}

export function removeToken() {
  return localStorage.setItem(TokenKey, '')
}

设置环境变量

创建生产环境文件.env.production

MODE = 'production'
VITE_APP_BASE_PREFIX = '/accountApi'

创建开发环境文件.env.development

MODE = 'development'
VITE_APP_BASE_PREFIX = '/api'
VITE_APP_BASE_API = http://localhost:6001

对原始的vite.config.ts文件稍加改造

跨域配置

vite.config.ts文件添加如下配置,与plugins同一级别

    server: {
      proxy: {
        [config.VITE_APP_BASE_PREFIX]: {
          target: config.VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: (path) =>
            path.replace(new RegExp(`^${config.VITE_APP_BASE_PREFIX}`), ''),
        },
      },
    }

封装axios

创建文件utils/request.ts

import axios from 'axios'
import { useStaffStore } from '@/store/staffStore'
import { getToken } from '@/utils/auth'

const service = axios.create({
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  timeout: 20000, // request timeout
})

service.interceptors.request.use(
  (config) => {
    const staffStore = useStaffStore()
    config.baseURL = import.meta.env['VITE_APP_BASE_PREFIX']

    if (staffStore.token) {
      config.headers['x-authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const staffStore = useStaffStore()
    const res = response.data
    if (res.code === 401) {
      alert(res.msg);

      staffStore.logOut()
      return Promise.reject(res)
    } else if (res.code !== 200) {
      alert('网络错误,请稍后重试');
      return Promise.reject(res)
    } else {
      return res
    }
  },
  (error) => {
    console.log(error) // for debug
    const errContent = error.response
    const staffStore = useStaffStore()
    if (errContent?.status === 401) {
      alert(errContent.data.msg)
      staffStore.logOut()
      return Promise.reject(error)
    } else {
      alert(errContent?.data?.msg || '网络错误,请稍后重试')
      return Promise.reject(error)
    }
  }
)

export default service