马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
1. 前端代理(开发环境推荐)
实用场景:Vue 开发环境调试时,避免直接请求后端接口的跨域问题。
实现步骤:
- 在 Vue 项目的 vue.config.js 中配置代理:
- module.exports = {
- devServer: {
- proxy: {
- '/api': { // 代理所有以 /api 开头的请求
- target: 'http://localhost:8080', // Spring Boot 后端地址
- changeOrigin: true, // 允许跨域
- pathRewrite: {
- '^/api': '' // 去除请求路径中的 /api 前缀
- }
- }
- }
- }
- }
复制代码 2.前端请求时使用 /api 前缀:
- axios.get('/api/users').then(response => {
- // 处理响应
- });
复制代码 优点:无需修改后端代码,恰当开发阶段快速解决跨域。
2. 后端全局配置 CORS(生产环境推荐)
实用场景:生产环境需要后端直接支持跨域。
实现步骤:
- 在 Spring Boot 中创建全局 CORS 配置类:
- @Configuration
- public class CorsConfig implements WebMvcConfigurer {
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/**") // 所有接口
- .allowedOrigins("http://localhost:5173") // 允许的前端地址
- .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
- .allowedHeaders("*") // 允许的请求头
- .allowCredentials(true) // 允许发送 Cookie
- .maxAge(3600); // 预检请求缓存时间(秒)
- }
- }
复制代码 2.若使用 Spring Security,需额外放行 OPTIONS 请求(预检请求):
- @Configuration
- @EnableWebSecurity
- public class SecurityConfig {
- @Bean
- public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
- http.cors() // 启用 CORS
- .and()
- // 其他安全配置...
- .authorizeRequests()
- .requestMatchers(HttpMethod.OPTIONS).permitAll() // 放行 OPTIONS 请求
- .anyRequest().authenticated();
- return http.build();
- }
- }
复制代码
3. 后端注解配置(按接口控制)
实用场景:仅特定接口需要跨域支持。
实现步骤:在 Controller 或方法上添加 @CrossOrigin 注解:- @RestController
- @CrossOrigin(origins = "http://localhost:5173") // 类级别注解
- public class UserController {
- @GetMapping("/users")
- @CrossOrigin(origins = "http://localhost:5173") // 方法级别注解
- public List<User> getUsers() {
- // 业务逻辑
- }
- }
复制代码 4. Nginx 反向代理(生产环境终极方案)
实用场景:前后端部署到同一域名下,彻底避免跨域。
实现步骤:
- 配置 Nginx,将前端请求代理到后端接口:
- server {
- listen 80;
- server_name your-domain.com;
- # 前端静态资源
- location / {
- root /path/to/vue/dist;
- index index.html;
- try_files $uri $uri/ /index.html;
- }
- # 后端 API 代理
- location /api {
- proxy_pass http://localhost:8080;
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- }
- }
复制代码 2.重启 Nginx:
总结
方案实用场景优点缺点前端代理开发环境无需后端改动,快速解决跨域仅实用于开发环境后端全局 CORS生产环境同一管理,安全性可控需后端配置注解配置特定接口跨域灵活控制单个接口配置冗余,维护成本高Nginx 反向代理生产环境部署彻底解决跨域,提升性能需运维支持推荐组合:
- 开发环境:前端代理(方案1) + 后端全局 CORS(方案2)。
- 生产环境:Nginx 反向代理(方案4) + 后端全局 CORS(方案2,双重保障)。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|