什么是跨域
跨域(Cross-Origin)是浏览器出于安全考虑,对不同源的资源访问施加的限制机制。其核心原因是同源策略(Same-Origin Policy),即浏览器仅允许协议(Protocol)、域名(Domain)、端口(Port)三者完全相同的页面进行资源交互,否则会触发跨域问题。
常见于前后端分离开发(如前端运行在 http://localhost:3000
,后端接口在 http://api.example.com
)、CDN 资源加载、第三方 API 调用等。
跨域是浏览器的安全拦截机制,跨域请求并非完全失败,而是浏览器在接收到响应后主动拦截。例如,后端可能正常返回数据,但浏览器因检测到跨域而拒绝处理响应。
跨域的解决方案
JSONP(JSON with Padding)
利用 <script>
标签的跨域加载特性,通过回调函数传递数据。
仅支持 GET 请求,安全性较低(易受 XSS 攻击),逐渐被 CORS 取代。(不推荐)
CORS(跨域资源共享)
通过服务器设置 HTTP 响应头(如 Access-Control-Allow-Origin
)声明允许访问的域名。(推荐)
代理服务器
前端请求同源代理服务器,由代理转发到目标服务器,绕过浏览器限制。(推荐)
springboot项目中如何支持CORS
使用 @CrossOrigin
注解
最简单的方式是在控制器类或方法上使用 @CrossOrigin
注解
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "https://example.com") // 类级别
public class MyController {@GetMapping("/data")@CrossOrigin(origins = {"https://example.com", "https://another.com"}) // 方法级别public ResponseEntity<String> getData() {return ResponseEntity.ok("Hello from Spring Boot 3!");}
}
全局 CORS 配置
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") // 所有路径.allowedOrigins("https://example.com", "https://another.com") // 允许的源.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法.allowedHeaders("*") // 允许的头部.allowCredentials(true) // 是否允许凭证.maxAge(3600); // 预检请求的缓存时间(秒)}
}