跨域问题has been blocked by CORS policy: No Access-Control-Allow-Origin和 It does not have HTTP ok status
SpringBoo vue项目发布到服务器出现跨域问题has been blocked by CORS policy: No Access-Control-Allow-Origin 和Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.解决springboo
·
SpringBoot vue项目发布到服务器出现跨域问题has been blocked by CORS policy: No Access-Control-Allow-Origin 和 Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
解决springboot项目和Vue项目部署到同一个服务器出现跨域请求问题
has been blocked by CORS policy: No Access-Control-Allow-Origin
网上找了很多方案 列了出来
**
解决方案
加一个过滤器和一个config配置类
@Slf4j
@Configuration
public class AccessControlAllowOriginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
log.info("经过了跨域处理过滤器。。。。。");
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-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token, content-type");
if (request.getMethod().equals(HttpMethod.OPTIONS.name())){
response.setStatus(HttpStatus.NO_CONTENT.value());
}else{
chain.doFilter(req, response);
}
}
@Override
public void destroy() {
}
}
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 配置所有请求
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
这是一种解决方案
第二种
在Spring Boot中拥有大量的注解,针对跨域问题,也提供了对应的注解@CrossOrigin,使用方法如下:
@CrossOrigin(origins = "*")
@RequestMapping(value = "/get")
public Result get() {
}
但是第二种方案需要每个接口都加注解 出于统一处理的便捷性还是加个过滤器吧
以上两种种亲测都可行
但是问题来了 如果以上方式加了还报错 并且response的header正常 错误如下
Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
原因就是浏览器的预检请求失败 即option请求失败 需要后端放行option请求即可
在spring security放行option请求
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
终于解决了!!!
更多推荐
已为社区贡献1条内容
所有评论(0)