Spring Cloud (6) | spring cloud zuul 跨域问题No 'Access-Control-Allow-Origin' header
发布日期:2021-06-30 12:19:24 浏览次数:2 分类:技术文章

本文共 1692 字,大约阅读时间需要 5 分钟。

在用spring cloud zuul做Filter的时候,访问微服务出现跨域问题,在网上找了很多办法:

zuul:  ignored-headers: Access-Control-Allow-Credentials, Access-Control-Allow-Origin

参照:

这个,发现还是没解决问题,

方法1

于是在Filter里面改代码解决了问题:
CloudFilter.java

@Componentpublic class CloudFilter extends ZuulFilter {
@Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletResponse response = ctx.getResponse(); response.addHeader("Access-Control-Allow-Origin", "*"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8");}}

方法2

在@EnableZuulProxy注解里的Class类加入下面这个Bean:
用到CorsFilter这个类,需要import org.springframework.web.filter.CorsFilter;

@Bean    public CorsFilter corsFilter() {        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();        final CorsConfiguration config = new CorsConfiguration();        config.setAllowCredentials(true);        config.addAllowedOrigin("*");        config.addAllowedHeader("*");        config.addAllowedMethod("OPTIONS");        config.addAllowedMethod("HEAD");        config.addAllowedMethod("GET");        config.addAllowedMethod("PUT");        config.addAllowedMethod("POST");        config.addAllowedMethod("DELETE");        config.addAllowedMethod("PATCH");        source.registerCorsConfiguration("/**", config);        return new CorsFilter(source);    }

参照:

更多系列文章推荐:

转载地址:https://java-basketball.blog.csdn.net/article/details/78680092 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Spring Cloud (12) | Spring Cloud Zuul网关调用微服务,request请求参数是application/json
下一篇:mysql中 truncate() 和 format() 的区别

发表评论

最新留言

很好
[***.229.124.182]2024年04月25日 02时17分31秒