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 }
  • 相关阅读:
    hdu1814 Peaceful Commission 2-SAT
    上传下载文件
    文件下载类
    文件操作类
    MD5加密帮助类
    加密解密类
    发送邮件函数
    DataTable 分页
    服务器缓存帮助类
    Cookie帮助类
  • 原文地址:https://www.cnblogs.com/lprosper/p/10188841.html
Copyright © 2011-2022 走看看