@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {
...
}
/**
* 支持跨域资源共享-CORS 配置
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
/**
* addMapping: /** 表示所有路径及子路径下的 HTTP 应答都进行 Access-Control 标头包装
* allowedOrigins: response header 中增加 Access-Control-Allow-Origin: * (表示允许所有 Origin 来源的跨域请求)
* allowedMethods:response header 中增加 Access-Control-Allow-Methods: * (表示允许所有 HTTP Method)
* allowedHeaders:response header 中增加 Access-Control-Allow-Headers: *
* maxAge:response header 中增加 Access-Control-Max-Age: 1800 (表示建议浏览器缓存预检【Options请求】结果 1800s,可以降低服务端处理预检请求的压力)
*
* 配置解释参考:https://cloud.tencent.com/developer/article/1513418
*/
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.maxAge(1800);
}
}
同源请求不返回Access-Control-Allow-Origin处理方法
- 如果 Origin 和 请求的 Url 地址是同源的( HTTP Method + host + port 完全一致则认为同源),则 Spring 框架并不会在 Response Header 中应答 Access-Control-Allow-Origin: * ,“同源访问时Spring不会返回Access-Control-Allow-Origin标头”
#方法一 在 Controller 方法上手工给 HttpServletResponse增加 header
response.setHeader("Access-Control-Allow-Origin", "*");
#方法二 自定义一个CorsFilter 手工添加
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
@WebFilter(filterName="CorsFilter")
@Configuration
public class CorsFilter implements Filter {
/**
* 添加头部跨域过滤器(解决同源跨域问题)
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Token, Authentication");
chain.doFilter(req, res);
}
}