問題描述: vue項(xiàng)目使用axios 請(qǐng)求 在 安卓和pc端正常請(qǐng)求 但是在ios(ios12是我們遇到的)上會(huì)出現(xiàn) 跨域 預(yù)請(qǐng)求失敗 導(dǎo)致 在catch會(huì)捕獲 Network error 味抖;
導(dǎo)致問題出現(xiàn)的原因: 是由于header里面帶了很多請(qǐng)求參數(shù)咳焚,而后端設(shè)置的response.setHeader("Access-Control-Allow-Headers", "*");允許所有頭部沒有生效導(dǎo)致铜犬。 但是在PC瀏覽器或者安卓手機(jī)上所宰,該方式又能生效(煩人的IOS兼容問題喇澡,找了好久才找到)犯眠。最終通過后臺(tái)修改跨域配置解決ios請(qǐng)求兼容請(qǐng)問題类垫;
//改造前
@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);
}
}