解决No 'Access-Control-Allow-Origin' header is present on the requested resource.跨域问题

跨域错误

解决No 'Access-Control-Allow-Origin' header is present on the requested resource.跨域问题_第1张图片

 

错误原因

 

解决方法

在后台写一个过滤器过滤器来改写请求头头

CorsFilter.java

public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest)servletRequest;

        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String method = request.getMethod();
        if(method.equalsIgnoreCase("OPTIONS")){
            servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}

备注:

在web.xml文件中添加代码


    corsFilter
    xxx.xxx.CorsFilter


    corsFilter
    /*

 

你可能感兴趣的:(No,解决跨域问题)