采取前后端分离的开发方式,前端、后端代码一般部署在不同的服务器上。这时后端代码就要配置跨域请求才能允许前端访问。在 Spring Boot 应用中配置跨域访问(CORS)可以通过多种方式来实现。以下是一些常见的方法:
1. 使用 @CrossOrigin
注解
你可以直接在 Controller 类或方法上使用 @CrossOrigin
注解来允许跨域请求。例如:
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@CrossOrigin(origins = "http://example.com")
@GetMapping("/my-endpoint")
public String myEndpoint() {
return "Hello, World!";
}
}
在上面的例子中,@CrossOrigin
注解允许来自 http://example.com
的跨域请求访问 /my-endpoint
路径。
2. 使用全局 CORS 配置
如果你想要为整个应用配置 CORS,你可以创建一个配置类并覆盖 WebMvcConfigurer
的 addCorsMappings
方法:
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 WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许所有路径的跨域请求
.allowedOrigins("http://example.com") // 允许的源
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
.allowedHeaders("*") // 允许的请求头
.allowCredentials(true); // 是否允许携带凭证
}
}
在这个例子中,我们配置了一个全局的 CORS 设置,它允许来自 http://example.com
的跨域请求访问所有路径,并允许 GET、POST、PUT 和 DELETE 方法。
3. 使用 CorsFilter
Bean
你还可以创建一个 CorsFilter
的 Bean 并将其添加到 Spring 容器中。这通常涉及使用 UrlBasedCorsConfigurationSource
:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://example.com");
corsConfiguration.addAllowedMethod("GET", "POST", "PUT", "DELETE");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
在这个例子中,我们创建了一个 CorsFilter
的 Bean,它使用 UrlBasedCorsConfigurationSource
来定义哪些路径应该应用哪些 CORS 配置。
4. 使用 application.properties
或 application.yml
对于简单的 CORS 配置,你也可以在 application.properties
或 application.yml
文件中设置属性:
# application.yml
spring:
mvc:
cors:
add-mappings: true
mapping-sources: classpath:/cors-mappings.properties
然后在 cors-mappings.properties
文件中定义具体的 CORS 映射:
# cors-mappings.properties
/my-endpoint=http://example.com
注意:这种方法不如前几种方法灵活,因此它通常用于简单的用例。
选择哪种方法取决于你的具体需求和你想要控制的粒度。对于大多数应用来说,使用全局 CORS 配置或 @CrossOrigin
注解就足够了。然而,如果你需要更细粒度的控制,那么可能需要使用 CorsFilter
或 UrlBasedCorsConfigurationSource
。