• Spring boot Access-Control-Allow-Origin 问题解决


    Spring boot Access-Control-Allow-Origin 问题解决


    最近在做一个项目,前后端分离,后端使用的框架是Spring boot,后端接口在使用swagger测试接口时没有问题,前端调用接口时,控制台发生关于“Access-Control-Allow-Origin” 的报错

    Failed to load http://192.168.*.*:8888/system/list?page=0&size=999: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://192.168.*.*:8089' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
    

    相关知识点

    什么是跨域?

    1、当两个域具有相同的协议(如http), 相同的端口(如80),相同的host(如www.google.com),那么我们就可以认为它们是相同的域(协议,域名,端口都必须相同)。
    2、跨域就指着协议,域名,端口不一致,出于安全考虑,跨域的资源之间是无法交互的(例如一般情况跨域的JavaScript无法交互,当然有很多解决跨域的方案)

    Access-Control-Allow-Origin

    Access-Control-Allow-Origin是HTML5中定义的一种解决资源跨域的策略。

    他是通过服务器端返回带有Access-Control-Allow-Origin标识的Response header,用来解决资源的跨域权限问题。

    在Spring boot中的解决方式

    在Spring boot中通常是可以通过增加过滤器,对返回响应中的请求头增加相关配置,具体代码如下:

    /**
     * @Auther: yujuan 过滤器 解决跨域问题
     * @Date: 19-3-25 17:39
     * @Description:
     */
    @Component
    public class CorsFilter implements Filter {
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
    
            HttpServletRequest reqs = (HttpServletRequest) req;
    
            // response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            chain.doFilter(req, res);
        }
    
        @Override
        public void init(FilterConfig filterConfig) {}
    
        @Override
        public void destroy() {}
    
    }
    
    
  • 相关阅读:
    yarn安装ant-报错
    Linux扩展分区记录
    转载--tomcat调优
    转发:tomcat的acess_log打印post请求参数,分析日志
    经纬度差和米单位的换算
    loadrunner 11 安装与使用
    前端知识图谱
    linux-nc命令介绍
    双网卡设置(转:https://www.cnblogs.com/visionfeng/p/5825078.html)
    网络设备介绍
  • 原文地址:https://www.cnblogs.com/jakaBlog/p/10598325.html
Copyright © 2020-2023  润新知