前后端跨域的解决办法

文章目录

    • [1️⃣ CORS(最主流 ✅ 推荐)](#1️⃣ CORS(最主流 ✅ 推荐))
      • [✔ Spring Boot 实现方式一(推荐)](#✔ Spring Boot 实现方式一(推荐))
      • [✔ 方式二:@CrossOrigin(简单但不优雅)](#✔ 方式二:@CrossOrigin(简单但不优雅))
      • [✔ 方式三:Filter(企业常用🔥)](#✔ 方式三:Filter(企业常用🔥))
    • [2️⃣ Nginx 反向代理(生产环境王者 👑)](#2️⃣ Nginx 反向代理(生产环境王者 👑))
    • [3️⃣ 网关解决(微服务架构)](#3️⃣ 网关解决(微服务架构))

1️⃣ CORS(最主流 ✅ 推荐)

核心思路:

👉 后端加响应头,允许跨域

✔ Spring Boot 实现方式一(推荐)

全局配置:

java 复制代码
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowedOrigins("http://localhost:8080") // 前端地址
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true) // 允许cookie
                .maxAge(3600);
    }
}

✔ 方式二:@CrossOrigin(简单但不优雅)

java 复制代码
@RestController
@CrossOrigin(origins = "http://localhost:8080")
public class UserController {
}

👉 适合小项目 / 测试

👉 不适合生产(太分散)


✔ 方式三:Filter(企业常用🔥)

java 复制代码
@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        chain.doFilter(req, res);
    }
}

👉 优点:统一控制,权限清晰

👉 企业最常见写法


2️⃣ Nginx 反向代理(生产环境王者 👑)

核心思路:

👉 让前端和后端"看起来同源"

复制代码
server {
    listen 80;
    server_name yourdomain.com;

    location /api/ {
        proxy_pass http://localhost:8081/;
    }
}

前端调用:

复制代码
/api/user

👉 浏览器认为:

复制代码
同一个域名 ✔

👉 实际:

复制代码
Nginx帮你转发到后端

🔥 优点:

  • 不用改代码
  • 安全性高
  • 企业必备

3️⃣ 网关解决(微服务架构)

如果你用的是:

👉 Spring Cloud Gateway

配置:

复制代码
spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "http://localhost:8080"
            allowedMethods:
              - GET
              - POST

👉 所有服务统一跨域


相关推荐
脑子运行超载3 天前
Java动态生成PDF文件
java·pdf·状态模式·文件上传下载
喵叔哟4 天前
Day 2:先做一个能聊天的页面
状态模式
Arranging157885 天前
2026最新5款AI编程工具平替实测合集
状态模式
aaaa954726655 天前
2026最新5款AI编程工具平替实测合集
状态模式
chase_my_dream6 天前
FAST-LIO src/IMU_Processing.hpp 完整详细讲解
c++·状态模式·slam
前端不太难11 天前
Tool Graph:HarmonyOS PC 如何统一所有系统能力?
华为·状态模式·harmonyos
星恒随风24 天前
C++ string 类详解:常用接口、OJ 场景与模拟实现中的深浅拷贝
开发语言·c++·笔记·学习·状态模式
colofullove25 天前
实时游玩页与 WebSocket 状态管理实现
websocket·网络协议·状态模式
夏天测1 个月前
业务逻辑漏洞实战:篡改响应包绕过登录,直入后台管理系统
渗透测试·状态模式·业务逻辑漏洞·web 安全·响应包篡改
可乐ea1 个月前
【Spring Boot + MyBatis|第7篇】JWT 登录认证与拦截器实现
java·spring boot·后端·mybatis·状态模式