zoukankan      html  css  js  c++  java
  • 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() {}
    
    }
    
    
  • 相关阅读:
    用c语言程序判断谁是小偷
    android获取Button文本 从一个按钮开关中获取文本
    android 让一个控件按钮居于底部的几种方法
    java获取文件夹下所有文件的名称
    解决 apache error 指定网络名不再可用 "an unknown filter was not added: DEFLATE"的问题
    查看window隐藏进程,用微软的ProcessExplorer查看到电脑有个“硬件中断”占用大量CPU 解决办法
    Android中Message机制的灵活应用
    Thread和Looper以及Handler和Message详解 Android开发必读
    Android的Looper类使用的5个要点
    android的消息处理机制(图+源码分析)——Looper,Handler,Message
  • 原文地址:https://www.cnblogs.com/jakaBlog/p/10598325.html
Copyright © 2011-2022 走看看