zoukankan      html  css  js  c++  java
  • 2019-03-26 SpringBoot项目部署遇到跨域问题,记录一下解决历程

    近期SpringBoot项目部署遇到跨域问题,记录一下解决历程。

    1. 要严格限制,允许哪些域名访问,在application.properties文件里添加配置,配置名可以自己起:
      cors.allowed.origin=http://10.xx.253.xx:8081,http://localhost:4200
      做前后端分离的时候,这里允许的域名/IP一般都是前端项目所部署的机器。

    2. 添加一个配置类。@Configuration和@Bean注解一定要加上的。这样SpringBoot在启动的时候才会扫描到你这个类。这里的@Value("${cors.allowed.origin}")引用的就是在application.properties配置的跨域白名单。

    @Configuration
    public class CorsConfig {
    
        @Value("${cors.allowed.origin}")
        private String allowedOrigin;
    
        private CorsConfiguration buildConfig() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setAllowCredentials(true);
            corsConfiguration.setMaxAge(24 * 3600L);
            if (null != allowedOrigin) {
                String[] origins = allowedOrigin.split(",");
                for (String origin : origins) {
                    // 设置访问源地址
                    corsConfiguration.addAllowedOrigin(origin);
                }
            }
            // 设置访问源请求头
            corsConfiguration.addAllowedHeader("*");
            // 设置访问源请求方法
            corsConfiguration.addAllowedMethod("*");
            return corsConfiguration;
        }
    
        /**
         * Cors过滤器.
         */
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            // 对接口配置跨域设置
            source.registerCorsConfiguration("/**", buildConfig());
            return new CorsFilter(source);
        }
    }
    
    1. 正常情况下,启动项目就可以了。但是在实际中,我在CorsConfig类中打断点,发现并没有去加载这个配置类。于是在Application入口添加了下面的注解@ComponentScan(basePackages = {"com.xxx.xxx.xxx.web.config"})这里参数是CorsConfig所在的包名。这时候启动,在CorsConfig里面打断点就可以进来了。
  • 相关阅读:
    codeforces_1075_C. The Tower is Going Home
    leetcode_Stone Game_dp_思维
    leetcode_Counting Bits_dp
    Divide and Conquer_1.最大连续子数组
    python_MachineLearning_感知机PLA
    IIS中启用gzip压缩(网站优化)
    asp.net运行机制图
    asp.net 的那点事(2、浏览器和一般处理程序)
    asp.net 的那点事(1、当用户在浏览器地址栏输入了网址后,发生了什么?)
    android环境搭配 运行android sdk manager时出现错误问题解决
  • 原文地址:https://www.cnblogs.com/simuhunluo/p/10603412.html
Copyright © 2011-2022 走看看