跳到主要内容

跨域处理

什么是跨域?

跨域(Cross-Origin)是指浏览器从一个域名的网页去请求另一个域名的资源。出于安全考虑,浏览器默认会阻止跨域请求,这种行为被称为同源策略(Same-Origin Policy)。同源策略要求请求的协议、域名和端口必须完全一致,否则会被视为跨域请求。

在实际开发中,前后端分离的架构非常常见,前端和后端通常部署在不同的域名或端口下。因此,跨域问题成为了开发中必须解决的一个关键问题。


为什么需要跨域处理?

在前后端分离的架构中,前端应用(如 React、Vue)通常运行在一个域名下,而后端服务(如 Spring Boot)运行在另一个域名下。如果前端直接向后端发送请求,浏览器会阻止这种跨域请求,导致请求失败。

为了解决这个问题,我们需要在后端服务中配置跨域处理,允许特定的前端域名访问后端资源。


如何在 Spring Cloud Alibaba 中处理跨域?

Spring 提供了多种方式来处理跨域请求。以下是几种常见的解决方案:

1. 使用 @CrossOrigin 注解

@CrossOrigin 是 Spring 提供的一个注解,可以直接在控制器(Controller)或方法上使用,允许特定的跨域请求。

java
@RestController
public class MyController {

@CrossOrigin(origins = "https://frontend-domain.com")
@GetMapping("/api/data")
public String getData() {
return "Hello, this is cross-origin data!";
}
}

在上面的代码中,@CrossOrigin 注解允许来自 https://frontend-domain.com 的跨域请求访问 /api/data 接口。

2. 全局跨域配置

如果你希望为整个应用配置跨域,可以使用 WebMvcConfigurer 接口来实现全局跨域配置。

java
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 {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://frontend-domain.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}

在这个配置中,/api/** 路径下的所有接口都允许来自 https://frontend-domain.com 的跨域请求,并且支持 GETPOSTPUTDELETE 方法。

3. 使用 Spring Cloud Gateway 处理跨域

如果你的应用使用了 Spring Cloud Gateway,可以在网关层统一处理跨域请求。

yaml
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowed-origins: "https://frontend-domain.com"
allowed-methods: "*"
allowed-headers: "*"
allow-credentials: true
max-age: 3600

通过网关配置,所有经过网关的请求都会自动处理跨域问题。


实际案例

假设我们有一个前端应用运行在 https://frontend-app.com,后端服务运行在 https://backend-service.com。前端需要调用后端的 /api/user 接口获取用户信息。

后端代码

java
@RestController
public class UserController {

@CrossOrigin(origins = "https://frontend-app.com")
@GetMapping("/api/user")
public User getUser() {
return new User("John Doe", "john.doe@example.com");
}
}

前端代码

javascript
fetch('https://backend-service.com/api/user')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

在这个案例中,后端通过 @CrossOrigin 注解允许前端应用的跨域请求,前端可以成功获取用户信息。


总结

跨域处理是前后端分离架构中必须解决的问题。通过 Spring 提供的 @CrossOrigin 注解、全局跨域配置或 Spring Cloud Gateway 的跨域配置,我们可以轻松解决跨域问题,确保前后端的安全通信。

提示

在实际开发中,建议根据项目需求选择合适的跨域处理方式。如果项目规模较大,推荐使用全局配置或网关层统一处理跨域。


附加资源

  1. Spring 官方文档 - CORS 支持
  2. MDN Web Docs - 跨域资源共享 (CORS)

练习

  1. 尝试在你的 Spring Boot 项目中配置全局跨域,允许来自 http://localhost:3000 的请求。
  2. 使用 Spring Cloud Gateway 配置跨域,允许所有路径的请求来自 https://example.com