请帮帮忙。我正在使用Spring Cloud Gateway,我不断收到此Cors错误:
CORS策略已阻止从源“http://localhost:4200”访问位于“http://localhost:8084/users/files”的XMLHttpRequest:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
下面是我的application.yml文件
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*"
allowedMethods: "*"
下面是我的路由配置:
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/users/**")
.filters(f -> f.filter(authFilter))
.uri("http://localhost:8080/"))
.build();
}
这是我的CorsConfiguration文件。
public class CorsConfiguration {
private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Content-Length, Authorization, credential, X-XSRF-TOKEN";
private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS, PATCH";
private static final String ALLOWED_ORIGIN = "*";
private static final String MAX_AGE = "7200"; //2 hours (2 * 60 * 60)
@Bean
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
if (CorsUtils.isCorsRequest(request)) {
ServerHttpResponse response = ctx.getResponse();
HttpHeaders headers = response.getHeaders();
headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
headers.add("Access-Control-Max-Age", MAX_AGE); //OPTION how long the results of a preflight request (that is the information contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can be cached.
headers.add("Access-Control-Allow-Headers",ALLOWED_HEADERS);
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
};
}
}
4条答案
按热度按时间jtjikinw1#
你能像下面这样添加add-to-simple-url-handler-mapping属性到你的application.yml中,然后再试一次吗
cngwdvgl2#
在你的
CorsConfiguration
中,你只在它是一个CORS请求的时候设置CORS头,如果它是一个preflight请求,就不要设置。预检请求是失败的请求。因此,您需要删除if (CorsUtils.isCorsRequest(request))
条件。qacovj5a3#
对于maven用户,请尝试添加以下依赖项:
帮我搞定
ars1skjm4#
使用选项“allowed-origin-patterns:'*'“。允许所有CORS请求。