项目背景:
我们有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() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); //只过滤OPTIONS 请求 if(request.getMethod().equals(RequestMethod.OPTIONS.name())){ return false; } return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletResponse response = ctx.getResponse(); HttpServletRequest request = ctx.getRequest(); response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Credentials","true"); response.setHeader("Access-Control-Expose-Headers","X-forwared-port, X-forwarded-host"); response.setHeader("Vary","Origin,Access-Control-Request-Method,Access-Control-Request-Headers"); //允许继续路由 ctx.setSendZuulResponse(true); ctx.setResponseStatusCode(200); return null; } }