标签:路由 red get 过滤 后端 type 打开 请求 index
项目背景:
我们有web和大屏,以及移动端,需要访问微服务接口。
然而大屏时自己打开的网页,在网页中通过js调用我的webapi。出现了跨域情况。
原因:
出现这个问题,是由于跨域请求有2次请求。
第一次:options(查看请求可用性,确定请求后端是否支持请求类型)
第二次:才是你的真实请求。(get/post...)
PreFilter
/** * zuul转发前过滤器 */ @Component public class PreFilter extends ZuulFilter { public PreFilter() { super(); } @Override public String filterType() { return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { // return true; RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); //只过滤OPTIONS 请求 if(request.getMethod().equals(RequestMethod.OPTIONS.name())){ return true; } return false; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); HttpServletResponse response = ctx.getResponse(); response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Credentials","true"); response.setHeader("Access-Control-Allow-Headers","authorization, content-type"); response.setHeader("Access-Control-Allow-Methods","POST,GET"); String requestUrl = request.getRequestURL().toString(); String requestUri = request.getRequestURI(); String zuul = requestUrl.substring(0,requestUrl.indexOf(requestUri)); // zuul根路径 ctx.addZuulRequestHeader("zuul", zuul); //不再路由 ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(200); return null; } }
PostFilter(这个可以不要)
@Component public class PostFilter extends ZuulFilter { protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran"; @Override public String filterType() { return FilterConstants.POST_TYPE; } @Override public int filterOrder() { return -1; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { return null; } }
标签:路由 red get 过滤 后端 type 打开 请求 index
原文地址:https://www.cnblogs.com/hanjun0612/p/10783070.html