问题描述: vue项目使用axios 请求 在 安卓和pc端正常请求 但是在ios(ios12是我们遇到的)上会出现 跨域 预请求失败 导致 在catch会捕获 Network error ;
导致问题出现的原因: 是由于header里面带了很多请求参数,而后端设置的response.setHeader("Access-Control-Allow-Headers", "*");允许所有头部没有生效导致。 但是在PC浏览器或者安卓手机上,该方式又能生效(烦人的IOS兼容问题,找了好久才找到)。最终通过后台修改跨域配置解决ios请求兼容请问题;
//改造前
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*");
if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpStatus.NO_CONTENT.value());
} else {
filterChain.doFilter(request, response);
}
}
//改造后
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
/**cors modified start**/
StringBuilder headers = new StringBuilder();
Enumeration<String> headerNames = request.getHeaders("Access-Control-Request-Headers");
if(Objects.nonNull(headerNames)) {
while (headerNames.hasMoreElements()) {
headers.append(headerNames.nextElement()).append(",");
}
}
response.setHeader("Access-Control-Allow-Headers", headers.toString());
/**cors modified end**/
if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpStatus.NO_CONTENT.value());
} else {
filterChain.doFilter(request, response);
}
}