SpringCloudGateway配置跨域设置以及如何本地测试跨域
在Spring Cloud Gateway中配置跨域可以通过定义一个全局过滤器来实现。以下是配置全局跨域的示例代码:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.reactive.config.CorsRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.server.WebFilter;
import org.springframework.http.HttpHeaders;
import reactor.core.publisher.Mono;
@Configuration
public class GlobalCorsConfig {
@Bean
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
if (CorsUtils.isCorsRequest(request)) {
HttpHeaders requestHeaders = request.getHeaders();
ServerHttpResponse response = ctx.getResponse();
HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
HttpHeaders headers = response.getHeaders();
headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
headers.setAllowCredentials(true);
headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_Methods, "GET, POST, PUT, DELETE");
headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_Headers, requestHeaders.getAccessControlRequestHeaders().toString());
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
};
}
}
在本地测试跨域时,可以通过以下方法:
- 修改
hosts
文件,将要测试的域名指向本地IP(127.0.0.1)。 - 使用支持跨域的浏览器插件,例如Moesif Origin & CORS Changer。
- 使用代理服务器如nginx配置相关的代理规则来处理跨域请求。
以上方法可以帮助你在本地环境模拟跨域请求,从而进行测试。
评论已关闭