Spring解决前端font文件跨域问题
问题描述
访问https://www.abc.com/正常,访问https://abc.com/,
字体文件xxx.woff出现跨域问题403.
该文件放置在static目录下,web config> addInterceptors配置放行。
差异:访问https://abc.com
文件xxx.woff2是通过css请求的
普通js和css文件,referer为https://abc.com, no orign
而xxx. woff2的referer为https://www.abc.com,origin为https://abc.com
一、使用**Filter**方式进行设置
使用Filter过滤器来过滤服务请求,向请求端设置Response Header(响应头部)的Access-Control-Allow-Origin属性声明允许跨域访问。
@WebFilter
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-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
}
二、实现 WebMvcConfigurer
@Configuration
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
public class AppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 拦截所有的请求
.allowedOrigins("http://www.abc.com") // 可跨域的域名,可以为 *
.allowCredentials(true)
.allowedMethods("*") // 允许跨域的方法,可以单独配置
.allowedHeaders("*"); // 允许跨域的请求头,可以单独配置
}
}
点评
亲测,两种方式都可生效,方式二地址后面不要加反斜杠,和前端request的origin保持一致
参考
JAVA | Java 解决跨域问题 花式解决跨域问题-腾讯云开发者社区-腾讯云
正文到此结束