问题描述: 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);
    }
}

 

找到问题后,开始对上面的代码进行了改造,由于项目中不同地方的接口可能header中的某些参数不一致,所以决定采用前端传了什么header,就在response中设置允许什么header,改造后的代码如下。

@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);
    }
}

 

 解决问题参考地址:

  1: https://github.com/axios/axios/issues/1598

  2: https://blog.csdn.net/biakia0610/article/details/103777597

  3: https://blog.csdn.net/Daijianshi_123/article/details/102853654

 

posted on 2021-08-06 10:35  刘世涛6192  阅读(1067)  评论(0编辑  收藏  举报