package cn.space.gateway.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Configuration
public class CorsConfig {
_private static final String _ALLOWED_HEADERS
= “,version,content-type,apptype,authorization,clientversion,parkid,X-Requested-With”;
private static final String ALLOWED_METHODS = “
“;
private static final String ALLOWED_ORIGIN = ““;
private static final String ALLOWED_EXPOSE = “
“;
private static final String MAX_AGE = “3600”;

@Bean
public WebFilter corsFilter() {
_return
(ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
String url = request.getPath
().toString();
if
(CorsUtils._isCorsRequest(_request)) {
ServerHttpResponse response = ctx.getResponse();
HttpHeaders headers = response.getHeaders
();
headers.add
(“Access-Control-Allow-Origin”, request.getHeaders().getFirst(HttpHeaders._ORIGIN));
headers.add(“Access-Control-Allow-Methods”, ALLOWED_METHODS);
headers.add(“Access-Control-Max-Age”, MAX_AGE);
headers.add(“Access-Control-Allow-Headers”, ALLOWED_HEADERS);
headers.add(“Access-Control-Expose-Headers”, ALLOWED_EXPOSE);
headers.add(“Access-Control-Allow-Credentials”, “true”);

  1. if _(_request.getMethod_() _== HttpMethod._OPTIONS) {<br /> _response.setStatusCode_(_HttpStatus._OK)_;<br /> return Mono._empty()_;<br /> _}<br /> }<br /> _return chain.filter_(_ctx_)_;<br /> _}_;<br /> _}

}_

yml配置

  1. spring:
  2. cloud:
  3. gateway:
  4. default-filters:
  5. - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials Vary, RETAIN_LAST
  6. discovery:
  7. locator:
  8. enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
  9. globalcors:
  10. corsConfigurations:
  11. '[/**]':
  12. allowedOrigins: "*"
  13. allowedMethods: "*"