云浮网站建设推广赚钱的微信小程序
对于springboot加vue项目中
vue前端页面,在发送请求时,如:axios.get(‘/api/thing/list’)如果是相对地址,前端会自动拼接前端所运行的地址如http://localhost:5173/api/thing/list但是如果你在vite.config.js中配置了代理
server: {proxy: {'/api': {target: 'http://localhost:9100', // 后端地址changeOrigin: true,rewrite: (path) => path.replace(/^\/api/, ''), // 可选:是否移除 /api 前缀}}}
那么
-
代理行为:
-
当浏览器请求
http://localhost:5173/api/thing/list
时,Vite 服务器会拦截该请求。 -
代理到
http://localhost:9100/api/thing/list
(如果没配置rewrite
)。 -
如果配置了
rewrite: (path) => path.replace(/^\/api/, '')
,则代理到http://localhost:9100/thing/list
。
-
前提是:你写的前端请求时相对地址,不是完整的路径,如果你的前端请求写的是完整 URL(如 http://127.0.0.1:9100/api/thing/list
),Vite 代理不会生效。
如果你在前端代码中 直接写完整的后端地址(如 http://127.0.0.1:9100/api/thing/list
),一定会触发 CORS 跨域问题,因为:
1. 为什么会出现 CORS 问题?
-
浏览器同源策略:当你的前端页面运行在
http://localhost:5173
,而请求发往http://127.0.0.1:9100
时:-
协议 (
http
)、域名 (localhost
vs127.0.0.1
)、端口 (5173
vs9100
) 三者任一不同,均会被视为跨域。 -
即使
localhost
和127.0.0.1
指向同一台机器,浏览器仍会认为它们是不同源!
-
-
触发条件:
浏览器会先发送一个OPTIONS
预检请求(Preflight),如果后端没有返回正确的 CORS 响应头(如Access-Control-Allow-Origin
),请求会被拦截。
2. 如何解决?
方案 1:改用 Vite 代理(推荐)
-
优势:前端代码只需写相对路径(如
/api/thing/list
),由 Vite 代理转发到后端,规避跨域问题。 -
配置:
javascript
复制
下载
// vite.config.js export default defineConfig({server: {proxy: {'/api': {target: 'http://127.0.0.1:9100', // 后端地址changeOrigin: true,rewrite: (path) => path.replace(/^\/api/, ''), // 可选:去掉 /api 前缀}}} });
-
前端代码:
javascript
复制
下载
// ✅ 会被代理到 http://127.0.0.1:9100/thing/list axios.get('/api/thing/list');
方案 2:后端配置 CORS(需修改后端代码)
如果必须直接请求 http://127.0.0.1:9100
,后端需添加以下响应头:
java
复制
下载
// Spring Boot 示例 @Configuration public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("http://localhost:5173") // 允许的前端地址.allowedMethods("*").allowCredentials(true);} }
方案 3:修改前端请求地址(临时方案)
-
将
127.0.0.1
改为localhost
,确保域名一致:javascript
复制
下载
// ✅ 如果后端和前端都用 localhost,可能避免跨域(但端口仍需一致) axios.get('http://localhost:9100/api/thing/list');
-
局限性:
如果端口不同(如前端5173
,后端9100
),仍需代理或 CORS。