• Spring Boot跨域处理



    📃个人主页:不断前进的皮卡丘
    🌞博客描述:梦想也许遥不可及,但重要的是追梦的过程,用博客记录自己的成长,记录自己一步一步向上攀登的印记
    🔥系列专栏:Spring Boot系列专栏

    跨域处理

    跨域问题演示

    我们先来演示一下跨域问题,后端代码参照上一篇博客
    image.png
    image.png
    如果在前端想要获取班级的数据,就应该给后端发送一个get请求
    image.png
    但是我们可以发现出错了
    image.png

    跨域概述

    • 跨域问题:在前后端分离开发过程中,前后端程序独立部署在不同的服务器,默认是拒绝跨域的
    • 跨域问题产生原因:在设计HTTP协议的时候,为了保证数据的安全,定义了同源同策规则,就比如我们的qq不能发消息给微信一样,所以不允许跨域访问
    • 跨域问题的解决方案:
      • 后端处理
      • 前端处理
      • 中间反向代理服务器

    什么是跨域,跨域解决方案

    讲跨域的话,那我们就得了解一下同源策略。同源策略是由Netscape提出的一个著名的安全策略,它是浏览器最核心也是最基本的安全功能,现在所有支持JavaScript的浏览器都会使用这个策略。
    同源是指协议、域名、端口要相同。同源策略是基于安全方面的考虑提出了的,这个策略本身是没有问题的,但是我们在实际开发中,因为各种原因又经常会有跨域的需求,传统的跨域方案是JSONP,JSONP虽然可以解决跨域,但是有一个很大的局限性,那就是它只支持GET请求,不支持其他类型的请求

    本篇文章要说的是CORS(Cross-origin resource sharing,跨域源资源共享),是一个W3C标准,它是一份浏览器技术的规范,提供了Web服务从不同网域传来沙盒脚本的方法,以避开浏览器的同源策略,这是JSONP模式的现代版,在Spring框架中,对于CORS也提供了相应的解决方案。

    解决方法

    在方法上使用@CrossOrigin

     /**
         * 查询所有班级信息
         */
        @GetMapping("/school/cls")
        //所有的客户端请求都运行
        //@CrossOrigin
        //参数:限制前端跨域的地址
        @CrossOrigin(value = "http://localhost:8848")
        public ResultInfo queryAllCls() {
            ResultInfo info = new ResultInfo();
            try {
                List<Cls> clsList = clsService.queryAllCls();
                info.setCode(200);
                info.setOk();
                info.setData(clsList);
    
            } catch (Exception e) {
                e.printStackTrace();
                info.setError();
    
            }
            return info;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    image.png

    自定义全局配置类

    这种方式不适合带请求头的方式

    /**
     * @author zengyihong
     * @create 2022--08--16 17:56
     */
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        /**
         * addMapping:允许哪一些资源路径被跨域
         * allowedOrigins:允许哪些资源被跨域
         * allowedMethods:允许哪些请求方式被跨域
         * allowCredentials:是否使用缓存机制
         * maxAge:跨域请求的超时时间
         * @param registry
         */
        @Override
        public void addCorsMappings(CorsRegistry registry) {
    
             registry.addMapping("/**")
                     .allowedOrigins("*")
    //                 .allowedOrigins("http://localhost:8080","http://localhost:88848")
                     .allowedMethods("*")
    //                 .allowedMethods("GET","POST","DELETE","PUT")
                     .allowCredentials(false)
                     .maxAge(3600);
        }
    }
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    自定义跨域过滤器

    package com.zyh.springboot.config;
    
    
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;
    
    /**
     * @author zengyihong
     * @create 2022--08--16 19:04
     */
    @Configuration
    public class CustomCorsFilter {
        @Bean
        public FilterRegistrationBean corsFilter(){
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(false);//表示是否允许请求带有验证信息
            config.addAllowedOrigin("*");//表示允许所有,可以设置需要的地址
            config.addAllowedHeader("*");
            config.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", config);//CORS配置对所有接口都有效
            FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
            bean.setOrder(3600);
            return bean;
    
    
    
    
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    image.png

  • 相关阅读:
    16:状态模式
    golang - recover 使用笔记
    硬盘那些事(硬盘的分类)
    K8S(七):关于Volume,PersistentVolume(PV),persistentVolumeClaim(PVC)
    将一个字符串str的内容颠倒(逆序)过来,并输出
    为什么国外程序员的创造力比中国程序员强?
    【PDF合并】利用 Python 合并 PDF 文件
    IBM MQ 连接属性-示例
    高精度电压源是什么意思
    怎样合并PDF文件更快速?PDF合并工具有什么?
  • 原文地址:https://blog.csdn.net/qq_52797170/article/details/126389060