赞
踩
1.在项目根目录下添加.env.development 和 .env.production 文件 (根据实际开发需求添加,比如 .env.text等)
(1) .env.development 文件内容
- // 开发环境
-
- ENV = 'development'
-
- VITE_BASE_URL='https://xxx'
(2) .env.production 文件内容
-
- // 生产环境
-
- ENV = 'production'
-
- VITE_BASE_URL='https://xxx'
-
-
2.找到package.json 文件 添加如下代码
- "scripts": {
- "dev": "vite",
- "build": "vite build",
- "preview": "vite preview",
- "build:prod": "vite build --mode production",
- "build:dev": "vite build --mode development"
- },
3. 找到vite.config.js,添加如下代码 完成 代理 配置
- import { defineConfig, loadEnv} from 'vite'
- import vue from '@vitejs/plugin-vue'
- // https://vitejs.dev/config/
- export default defineConfig(({ mode }) => {
- const config = loadEnv(mode, './')
- return {
- plugins: [
- vue(),
-
- ],
-
- server: {
- hmr:true,
- proxy: {
- '/api': {
- target: config.VITE_BASE_URL, //目标url
- changeOrigin: true, //支持跨域
- rewrite: (path) => path.replace(/^\/api/, ""),
- //重写路径,替换/api
- }
- }
- },
-
- }
- })

重点来啦!!!!!! 关于axios的二次封装
首先在项目中安装 axios, (基于node环境)
npm install axios
然后进行封装,新建一个js 文件 ($axios.js),代码如下:
- import axios from 'axios'
- import { ElMessage } from 'element-plus'
- import router from '@/router/index'
-
- // 创建axios实例
-
- const baseUrl = '/api/';
- const $axios = axios.create({
- baseURL: baseUrl,
- timeout: 200000 // 请求超时时间
- })
- let isRefreshing = true;
-
- // request拦截器
- $axios.interceptors.request.use(config => {
- if (localStorage.getItem("token")) {
- config.headers['Authorization'] = localStorage.getItem("token");
- } else {
- config.headers['Authorization'] = 'Basic cGM6cGM='
- }
- config.headers['Content-type'] = 'multipart/form-data'
- config.headers['clientType'] = 'PC'
-
- return config
- }, error => {
- Promise.reject(error)
- })
-
- // respone拦截器
- $axios.interceptors.response.use(
- response => {
- // const loadingInstance = ElLoading.service()
- // 接口请求失败; 与后端约定 10010 代表token失效 需要刷新token
- if (response.data.code == 10010) {
- if (isRefreshing) {
- return refreshToken().then((res) => {
- if (res.data.code == 1) {
- localStorage.setItem("token", "Bearer " + res.data.access_token);
- // 已经刷新了token,将所有队列中的请求进行重试
- onAccessTokenFetched();
- // 再发请求
- return instance(response.config);
- } else {
- localStorage.removeItem('token')
- router.push({ path: '/login' })
- return false
- }
- }).catch(() => {
- console.log('请求refreshToken接口异常', error)
- localStorage.removeItem('token')
- router.push({ path: '/login' })
-
- return false;
- }).finally(() => {
- isRefreshing = true
- })
- } else {
- // 正在刷新token 将失败401的请求放入队列
- const retryOriginalRequest = new Promise((resolve) => {
- addSubscriber(() => {
- resolve(instance(response.config))
- })
- });
- return retryOriginalRequest;
- }
- } else if (response.data.code !== 1) {
- ElMessage({
- message: response.data.message,
- type: 'error',
- duration: 2000
- })
-
- return response.data
-
- } else {
-
- return response.data
-
- }
- },
- error => {
- ElMessage({
- message: error.message,
- type: 'error',
- duration: 3 * 1000
- })
- router.push({ path: '/login' })
- return Promise.reject(error)
- }
- )
-
- export default $axios
-
- // 刷新token请求
- function refreshToken() {
- return axios.post(`${baseUrl}auth/oauth/token`,
- {
- 'grant_type': 'refresh_token',
- 'refresh_token': sessionStorage.getItem("screen_token")
- }, { headers: { 'Authorization': 'Basic cGM6cGM=', 'clientType': 'SCREEN', 'Content-type': 'multipart/form-data' } });
- }
-
- let subscribers = [];
-
- // 执行队列
- function onAccessTokenFetched() {
- subscribers.forEach((callback) => {
- callback();
- })
- subscribers = [];
- }
-
- // 添加队列
- function addSubscriber(callback) {
- subscribers.push(callback)
- }

使用方法:
新建一个api.js文件 : 代码如下
- import $axios from './$axios'
-
- // GET 请求方式
- export const getList = (data) => {
- return $axios({
- method: 'GET',
- url: 'xxx/xxx',
- params: data
- })
- }
-
- // POST请求方式
- export const upload = (data) => {
- return $axios({
- method: 'POST',
- url: 'xxx/xxx',
- data: data
- })
- }

在组件中的使用方式
- <script setup>
- import {ref} from 'vue'
- import { getList } from "@/assets/api/api.js";
-
- const list = ref([])
- const getData = async () => {
- let obj = {
- pageSize:10,
- pageNum:1
-
- }
-
- let res = await getList(obj)
- list.value = res.data.list
- }
-
- </script>

完成