springboot Access-Control-Allow-Origin怎么配置
时间: 2023-11-07 17:05:14 浏览: 90
在Spring Boot中配置`Access-Control-Allow-Origin`可以通过添加一个过滤器来实现。下面是配置的步骤:
1. 创建一个名为`CorsFilter`的类,实现`javax.servlet.Filter`接口。
2. 在`CorsFilter`类中,重写`doFilter`方法,并在方法中添加以下代码:
```java
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
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, Accept, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
}
```
3. 配置完成后,Spring Boot会将该过滤器自动应用于所有请求。在响应中将包含`Access-Control-Allow-Origin`标头,该标头的值设置为"*",表示允许来自任何域的请求。
阅读全文