0. 序
目标:
前端登录后,
1. axios安装
axios 是一个流行的 JavaScript 库,用于发送 HTTP 请求。要安装它,请打开终端或命令提示符,然后输入以下命令:
1
| npm install axios --save
|
1.2 Vue引入
找到main.ts
1 2 3 4
| import axios from 'axios';
app.config.globalProperties.$axios = axios;
|
1.3 自定义axios
在请求前加上/api/ 和请求头需要自定义axios方法:
创建 src/utils/request.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import axios from 'axios';
import { getToken } from './auth.js';
const service = axios.create({ baseURL: '/api', timeout: 5000, }); console.log('request.js 已加载,拦截器初始化完成');
service.interceptors.request.use( (config) => { console.log('=== 进入请求拦截器 ==='); const token = getToken(); console.log('拦截器中获取的token:', token); console.log('当前请求路径:', config.url); if (token) { config.headers['Access-Token'] = token; console.log('已添加请求头:', config.headers['Access-Token']); } else { console.log('token为空,未添加请求头'); } return config; }, (error) => { console.error('请求拦截器错误:', error); return Promise.reject(error); } );
service.interceptors.response.use( (response) => response, (error) => { console.error('接口请求失败:', error); if (error.response?.status === 401) { window.location.href = '/login'; } return Promise.reject(error); } );
export default service;
|
1.4 引入自定axios
在上述的main.ts中,去掉自带的axios。
1 2 3 4 5 6
|
import service from './utils/request.js'
app.config.globalProperties.$axios = service;
|
自此①已经实现
2. 路由转发
通过proxy进行跨域
在根目录下创建vite.config.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import { fileURLToPath, URL } from 'node:url' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueDevTools from 'vite-plugin-vue-devtools'
export default defineConfig({ plugins: [ vue(), vueDevTools(), ], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) }, }, server: { host: 'localhost', port: 5173, open: false, proxy: { '/api': { target: 'http://localhost:9998', changeOrigin: true, ws: true, rewrite: (path) => path.replace(/^\/api/, ''), configure: (proxy, options) => { proxy.on('proxyReq', (proxyReq, req, res) => { console.log(`[Proxy] ${req.method} ${req.url} -> ${options.target}${req.url.replace('/api', '')}`); }); } } } }, build: { outDir: 'dist', assetsDir: 'static', sourcemap: true, chunkSizeWarningLimit: 2000, rollupOptions: { output: { manualChunks: { 'vendor': ['vue', 'vue-router', 'vuex'] } } } }, css: { devSourcemap: true } })
|

再发送请求,可以看到服务被转发了自此②完成