vite2 + VUE3.0 Axios 二次封装
一. 安装 Axios
npm i axios
二. Axios 封装
1. src目录下创建api文件夹
2. api文件夹下创建axiosConfig.js文件
import Axios from 'axios'
const axios = Axios.create({
timeout: 20000 // 请求超时 20s
})
// 请求拦截
axios.interceptors.request.use(
(request) => {
// request.headers.Authorization = accessToken
return request
},
(error) => {
return Promise.reject(error)
}
)
// 响应拦截
axios.interceptors.response.use(
(response) => {
return response
},
(error) => {
return Promise.reject(error)
}
)
// vite: import.meta.env, webpack: process.env
const BASE_URL = import.meta.env.VUE_APP_URL
// 模块前缀统一配置
const SEVICE = {
AUTH: `${BASE_URL}/api/auth`,
SYS: `${BASE_URL}/api/sys`,
}
export { axios, BASE_URL, SEVICE }
3. api文件夹下创建各个模块文件
auth.js
import { axios, SEVICE } from '../axiosConfig'
let { AUTH } = SEVICE
// POST /auth/login
export const login = (params) => {
return axios.post(`${AUTH}/login`, params)
}
// GET /auth/getList
export const getList = () => {
return axios.get(`${AUTH}/getList`)
}
4. Axios 组件中使用
index.vue
<template>
<div>axios</div>
</template>
<script>
import { getList } from '@/api/auth'
export default {
created() {
getList()
.then((res) => {
console.log('res: ', res)
})
.catch((err) => {
console.log('err: ', err)
})
}
}
}
</script>
三. vue 设置代理
1. 修改 axiosConfig.js 设置
// vite: import.meta.env, webpack: process.env
const IS_DEV_ENV = import.meta.env.MODE === 'development'
// dev env use proxy
const BASE_URL = IS_DEV_ENV ? '/proxy' : import.meta.env.VUE_APP_URL
2. 修改 vite: vite.config.js , webpack: vue.config.ts
vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path')
// https://vitejs.dev/config/
export default defineConfig({
server: {
port: 8000, // 设置服务启动端口号
open: true, // 设置服务启动时是否自动打开浏览器
proxy: {
'/proxy': {
target: loadEnv(mode, process.cwd()).VITE_APP_URL,
changeOrigin: true,
ws: false,
rewrite: (path) => path.replace(/^\/proxy/, '')
}
}
},
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
},
base: './',
plugins: [vue()]
})