springboot跨域配置
时间: 2023-11-04 10:56:58 浏览: 31
在 Spring Boot 中配置跨域请求可以使用 @CrossOrigin 注解或者配置类的方式。
1. @CrossOrigin 注解
在 Controller 层的方法上添加 @CrossOrigin 注解即可实现跨域请求。例如:
```
@RestController
@RequestMapping("/api")
public class ApiController {
@CrossOrigin(origins = {"http://localhost:8080", "http://localhost:8081"})
@GetMapping("/user")
public User getUser() {
// ...
}
}
```
上面的代码表示允许来自 http://localhost:8080 和 http://localhost:8081 的跨域请求。
2. 配置类方式
创建一个配置类,添加 @Configuration 和 @EnableWebMvc 注解,并且实现 WebMvcConfigurer 接口,重写 addCorsMappings 方法。例如:
```
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:8080", "http://localhost:8081")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
```
上面的代码表示允许来自 http://localhost:8080 和 http://localhost:8081 的跨域请求,并且允许使用所有的请求方法和请求头,允许携带凭证,缓存时间为 3600 秒。
以上两种方式都可以实现跨域请求,选择适合自己的方式即可。