SpringCloud微服务解决网关跨域问题

写这篇文章之前我遇到了一个难以解决的CORS跨域问题

如图:

我也试了各种方式,比如网上常见的在Controller、接口上贴注解啊什么的

下面先列一下在此之前我尝试过的方式:

  • 1.在方法参数加HttpRsponseServlet:
response.setHeader("Access-Control-Allow-Origin", "*"); 
  • 2.在Controller或接口上贴@CrossOrigin注解

    @CrossOrigin
    // 我还尝试了各种给@CrossOrigin结果加参数,均无解
    public class XXXController{
        @GetMapping
        public List listUser(){
            return null;
        }
    }
    
  • 3.在SpringBoot配置过滤器,过滤请求

    以上配置均行不通!

    最后在GateWay网关的项目里加了这么个配置:

    private static final String MAX_AGE = "18000L";
    	@Bean
    	public WebFilter corsFilter() {
    		return (ServerWebExchange ctx, WebFilterChain chain) -> {
    			ServerHttpRequest request = ctx.getRequest();
    			if (!CorsUtils.isCorsRequest(request)) {
    				return chain.filter(ctx);
    			}
    			HttpHeaders requestHeaders = request.getHeaders();
    			ServerHttpResponse response = ctx.getResponse();
    			HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
    			HttpHeaders headers = response.getHeaders();
    			headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
    			headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
    			if (requestMethod != null) {
    				headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
    			}
    			headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    			headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
    			headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
    			if (request.getMethod() == HttpMethod.OPTIONS) {
    				response.setStatusCode(HttpStatus.OK);
    				return Mono.empty();
    			}
    			return chain.filter(ctx);
    		};
    	}
    

需要的import:

import org.springframework.http.HttpHeaders;
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 org.springframework.http.HttpMethod;
import reactor.core.publisher.Mono;
import org.springframework.context.annotation.Bean;
import static org.springframework.web.cors.CorsConfiguration.ALL;

如果你和我一样,请把这段配置加到gateway的启动类或者自己建个配置类(前提能被SpringBoot扫描到,必须是启动类的当前包及其子包,并加上@Configuration注解)


愿你出走半生,归来仍是少年