跨域错误
解决方法
在后台写一个过滤器来改写请求头
附上一个前端不知所以然的后台java代码:
1 public class CorsFilter implements Filter { 2 @Override 3 public void init(FilterConfig filterConfig) throws ServletException { 4 5 } 6 7 @Override 8 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 9 HttpServletResponse response = (HttpServletResponse) servletResponse; 10 HttpServletRequest request = (HttpServletRequest)servletRequest; 11 12 String origin = request.getHeader("Origin"); 13 response.setHeader("Access-Control-Allow-Origin", origin); 14 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 15 response.setHeader("Access-Control-Max-Age", "3600"); 16 // response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization"); 17 response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token"); // 解决vue-axios请求报错问题 18 response.setHeader("Access-Control-Allow-Credentials", "true"); 19 String method = request.getMethod(); 20 if(method.equalsIgnoreCase("OPTIONS")){ 21 servletResponse.getOutputStream().write("Success".getBytes("utf-8")); 22 }else{ 23 filterChain.doFilter(servletRequest, servletResponse); 24 } 25 } 26 27 @Override 28 public void destroy() { 29 30 } 31 }