zoukankan      html  css  js  c++  java
  • 解决No 'Access-Control-Allow-Origin' header is present on the requested resource.跨域问题(后台(java)解决方法)

    附:前端常见跨域解决方案(全)

    跨域错误

    解决方法

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

    附上一个前端不知所以然的后台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 }
  • 相关阅读:
    day74 作业
    day73 基表 表关联
    不知道第几次分享了
    day72 序列化家族
    day72 作业
    vscode
    vuex
    linux python3.7的安装和配置
    使用多线程分批发送短信代码,分割list
    docker 容器里使用crontab不生效
  • 原文地址:https://www.cnblogs.com/lprosper/p/10188841.html
Copyright © 2011-2022 走看看