springboot跨域
时间: 2023-07-07 17:42:55 浏览: 49
在 Spring Boot 中,可以通过配置 CORS(跨域资源共享)来解决跨域问题。具体步骤如下:
1. 添加依赖
在 pom.xml 中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 添加配置
在 Spring Boot 的配置文件中添加以下配置:
```yaml
spring:
security:
user:
name: admin
password: admin
cors:
allowed-origins: "*"
allowed-methods: GET, POST, PUT, DELETE
allowed-headers: "*"
allow-credentials: true
```
这里的 allowed-origins 配置是允许的跨域地址,"*" 表示允许所有来源。allowed-methods 配置是允许的 HTTP 方法,allowed-headers 配置是允许的 HTTP 头信息,allow-credentials 配置为 true 表示允许发送 cookie。
3. 在 Controller 中添加 @CrossOrigin 注解
在需要跨域的 Controller 上添加 @CrossOrigin 注解即可。例如:
```java
@RestController
@RequestMapping("/api")
@CrossOrigin
public class MyController {
// ...
}
```
这样,该 Controller 中的接口就可以跨域访问了。