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


    跨域错误


     

    错误原因


     

    解决方法
    在后台写一个过滤器过滤器来改写请求头头

    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文件中添加代码

    <filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>xxx.xxx.CorsFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
     
    ---------------------
    作者:汤姆猫丶
    来源:CSDN
    原文:https://blog.csdn.net/qq_39403545/article/details/82116121
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    Spring读取properties内容
    SpringBoot全局异常处理
    Hibernate入门
    Oracle查询表及注释
    MySQL重复与不重复问题
    IDEA中other settings不见了
    01程序员修炼之道
    团队冲刺(四)
    单词字母查询频率
    学习进度(9)
  • 原文地址:https://www.cnblogs.com/JAYIT/p/10938065.html
Copyright © 2020-2023  润新知