【vue】Access to XMLHttpRequest at ‘http://localhost:20001/toLogin‘ from origin ‘http://localhost:8080
前言报错信息:Access to XMLHttpRequest at 'http://localhost:20001/toLogin' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control c...
·
前言
报错信息:
Access to XMLHttpRequest at 'http://localhost:20001/toLogin' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
前端请求成功,后端返回200,然后前端到返回拦截器response前,报错了。
解决办法
参考文档1:https://segmentfault.com/q/1010000015817945
参考文档2:https://blog.csdn.net/qq_32625839/article/details/81001125
在过滤器里面加了response配置,且添加了cors跨域配置。但是依然报错。
解决方法:
https://www.jianshu.com/p/27a1072d831c
成功
代码
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
import java.util.List;
/**
* @author :qilong sun
* @date :Created in 2019/12/12 16:44
* @description:
* @modified By:
* @version: V1.0$
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AjaxCorsFilter extends CorsFilter {
public AjaxCorsFilter() {
super(configurationSource());
}
private static UrlBasedCorsConfigurationSource configurationSource() {
CorsConfiguration corsConfig = new CorsConfiguration();
List<String> allowedHeaders = Arrays.asList("x-auth-token", "content-type", "X-Requested-With", "XMLHttpRequest");
List<String> exposedHeaders = Arrays.asList("x-auth-token", "content-type", "X-Requested-With", "XMLHttpRequest");
List<String> allowedMethods = Arrays.asList("POST", "GET", "DELETE", "PUT", "OPTIONS");
List<String> allowedOrigins = Arrays.asList("*");
corsConfig.setAllowedHeaders(allowedHeaders);
corsConfig.setAllowedMethods(allowedMethods);
corsConfig.setAllowedOrigins(allowedOrigins);
corsConfig.setExposedHeaders(exposedHeaders);
corsConfig.setMaxAge(36000L);
corsConfig.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig);
return source;
}
}
更多推荐
已为社区贡献17条内容
所有评论(0)