为了在后端接口中允许跨域访问(CORS),你需要在你的Spring Boot项目中配置CORS。以下是几种实现方式:
方法一:使用全局CORS配置
这是在Spring Boot中最常用的方法之一,配置全局的CORS策略:
import org.springframework.context.annotation.Bean;
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 {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许跨域访问的路径
.allowedOrigins("http://example.com") // 允许跨域访问的域名
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
.allowedHeaders("*") // 允许的请求头
.allowCredentials(true) // 是否允许发送cookie
.maxAge(3600); // 预检请求的缓存时间(单位:秒)
}
};
}
}
方法二:在控制器方法级别配置CORS
如果你只想对特定的控制器或方法启用CORS,可以使用@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!";
}
}
方法三:全局过滤器配置CORS
你也可以通过配置过滤器来处理CORS请求:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CorsFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
public class MyCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*"); // 允许的域名,*表示允许所有
config.setAllowCredentials(true);
config.addAllowedMethod("*"); // 允许的方法
config.addAllowedHeader("*"); // 允许的请求头
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
关键点
allowedOrigins: 配置允许跨域访问的域名。使用*代表允许所有域名。allowedMethods: 配置允许的 HTTP 方法。allowedHeaders: 配置允许的请求头。allowCredentials: 配置是否允许发送 cookies。maxAge: 配置预检请求的缓存时间。
注意事项
- 为了安全,生产环境中最好不要使用
*作为allowedOrigins,而是明确指定允许跨域访问的域名。 - 如果需要允许带有凭据的请求(如 cookies),则
allowedOrigins不能使用*,必须明确指定具体的域名。
通过上述配置,你可以在Spring Boot项目中启用CORS,允许跨域访问。
1329

被折叠的 条评论
为什么被折叠?



