springboot 在服务器端设置响应头,添加Access-Control-Allow-Origin: *(通配符表示所有源)
时间: 2024-09-21 17:13:47 浏览: 112
在Spring Boot项目中,设置服务器响应头以支持CORS通常涉及到添加特定的过滤器或者配置全局的CORS策略。这里是一个基本的例子:
首先,你可以创建一个自定义的Filter,例如`CorsFilter.java`:
```java
import javax.servlet.*;
import java.io.IOException;
import org.springframework.stereotype.Component;
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 设置允许所有来源
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
// 允许跨域请求方法
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
// 允许携带的HTTP头部
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
// 允许预检请求(对于OPTIONS请求)
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Access-Control-Max-Age", "3600"); // 跨域缓存时间,单位秒
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { // 对于OPTIONS请求,直接返回
httpResponse.setStatus(HttpServletResponse.SC_OK);
return;
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}
```
然后,在Spring Boot的`WebMvcConfigurer`或`ConfigureApplication`中注册这个过滤器:
```java
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private CorsFilter corsFilter;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("*");
}
@Bean
public FilterRegistrationBean corsFilterRegistration() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(corsFilter);
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); // 将filter放在其他filter之前
return registrationBean;
}
}
```
这样,无论从哪个源发起请求,只要包含适当的CORS头部,Spring Boot应用都会响应并允许跨域。注意,将"*"替换为实际需要的源地址可能会更安全。
阅读全文