vite + axios 代理不起作用
先看官方示例
export default defineConfig({server: {proxy: {// 字符串简写写法'/foo': 'http://localhost:4567',// 选项写法'/api': {target: 'http://jsonplaceholder.typicode.com',changeOrigin: true,rewrite: (path) => path.replace(/^\/api/, '')},// 正则表达式写法'^/fallback/.*': {target: 'http://jsonplaceholder.typicode.com',changeOrigin: true,rewrite: (path) => path.replace(/^\/fallback/, '')},// 使用 proxy 实例'/api': {target: 'http://jsonplaceholder.typicode.com',changeOrigin: true,configure: (proxy, options) => {// proxy 是 'http-proxy' 的实例}},// Proxying websockets or socket.io'/socket.io': {target: 'ws://localhost:3000',ws: true}}}
})
这个是地址可以自己看去看
https://vitejs.cn/vite3-cn/config/server-options.html#server-open
我自己的情况
其实很简单
但是我的项目就是不行
一直显示404
这个是浏览器提示
很苦恼怎么改都不行,但是用postman是可以掉通的
最后解决
不过最后还是解决了,是自己理解错误了
baseUrl
这个地方不要填完整的地址写个名字或者不写都行
错误示例
const http = axios.create({baseURL: 'http://127.0.0.1:8888',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});
正确示例
const http = axios.create({baseURL: 'jvm',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});
vite.config.js
这个就更简单了,直接复制官方的就行
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'// https://vite.dev/config/
export default defineConfig({plugins: [vue()],server:{proxy:{'/jvm': {target: 'http://127.0.0.1:8888',changeOrigin: true,rewrite: (path) => {return path.replace(/^\/jvm/, '')}},}}
})
我实际的地址是 http://127.0.0.1:8888/api/hello
replace 之后就是正确的地址了
这就完了
是不是超简单
所以有问题多看官方文档,不要老搜索