济宁网站建设平台,自己在家怎么做电商,厦门正规网站建设多少,水利厅网站集约化建设对于springboot加vue项目中
vue前端页面#xff0c;在发送请求时#xff0c;如#xff1a;axios.get#xff08;‘/api/thing/list’)如果是相对地址#xff0c;前端会自动拼接前端所运行的地址如http://localhost:5173/api/thing/list但是如果你在vite.config.js中配置了…对于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/listVite 代理不会生效。 如果你在前端代码中 直接写完整的后端地址如 http://127.0.0.1:9100/api/thing/list一定会触发 CORS 跨域问题因为 1. 为什么会出现 CORS 问题 浏览器同源策略当你的前端页面运行在 http://localhost:5173而请求发往 http://127.0.0.1:9100 时 协议 (http)、域名 (localhost vs 127.0.0.1)、端口 (5173 vs 9100) 三者任一不同均会被视为跨域。 即使 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。