SpringBoot解决跨域问题(CROS)
问题:
前端请求后端出现下图类似问题:

Access to fetch at 'http://localhost:8081/user/page?pageNum=1&pageSize=2' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
解决:
再SpringBoot项目里面加上配置文件CorsConfig.java,重启之后即可实现跨域访问,不需要再在前端配置跨域设置。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
// 当前跨域请求最大有效时长(单位s)
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1、设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2、设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3、设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration); // 4、对接口配置跨域设置
return new CorsFilter(source);
}
}
本文介绍如何在SpringBoot项目中通过CorsConfig.java配置文件解决前端发起的跨域请求问题,提供详细的步骤和代码示例,确保跨域访问权限设置。

1万+

被折叠的 条评论
为什么被折叠?



