SpringBoot如何进行跨域处理
时间: 2023-07-04 22:19:26 浏览: 88
Spring Boot 可以通过添加 CORS 配置来进行跨域处理,具体步骤如下:
1. 在 Spring Boot 应用程序中添加 CorsFilter 过滤器。
```java
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
response.setHeader("Access-Control-Allow-Credentials", "true");
if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
```
2. 在 Spring Boot 应用程序的配置文件中添加配置。
```yaml
spring:
cors:
allowed-origins: "*"
allowed-methods: POST, GET, OPTIONS, DELETE
allowed-headers: Content-Type, Authorization, X-Requested-With
allow-credentials: true
max-age: 3600
```
以上是 Spring Boot 进行跨域处理的基本步骤,你可以根据具体情况调整配置内容。
阅读全文