在Spring Controller中添加CORS(跨源资源共享)支持。
例如,可以在Controller类上添加@CrossOrigin注解,设置允许来自特定域名的请求。示例如下:
@RestController
@CrossOrigin(origins = "http://example.com")
public class MyController {
// controller methods here
}
这样,来自http://example.com域名的请求就可以访问MyController中的方法了。
另一种方法是在Spring的配置文件中添加CORS配置。示例如下:
@Configuration
public class MyConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://example.com")
.allowedMethods("GET", "POST")
.allowedHeaders("header1", "header2")
.allowCredentials(true)
.maxAge(3600);
}
};
}
}
这样就可以允许http://example.com域名的请求访问/api/路径下的所有接口,支持的方法包括GET和POST,支持的头部字段包括header1和header2,同时允许携带cookie,缓存时间为3600秒。