Spring boot跨域设置

2019-11-05 16:32:10

参考地址 Spring boot跨域设置

1. 原由


本人是spring boot菜鸟,但是做测试框架后端需要使用Spring boot和前端对接,出现跨域问题,需要设置后端Response的Header.走了不少坑,在这总结一下以备以后使用


 


2. 使用场景


浏览器默认不允许跨域访问,包括我们平时ajax也是限制跨域访问的。


产生跨域访问的情况主要是因为请求的发起者与请求的接受者1、域名不同;2、端口号不同


 


3.解决方案


通过设置Access-Control-Allow-Origin来实现跨域访问


 


4. 具体解决


刚开始使用http://www.jianshu.com/p/f2060a6d6e3b设置,但是由于我们使用的spring版本的问题,CorsConfiguration类需要4.2.7版本。和我们使用的spring里面版本不一致,导致版本冲突或者各种问题


 


@Configuration

public class CorsConfig {

    private CorsConfiguration buildConfig() {

        CorsConfiguration corsConfiguration = new CorsConfiguration();

        corsConfiguration.addAllowedOrigin("*"); // 1

        corsConfiguration.addAllowedHeader("*"); // 2

        corsConfiguration.addAllowedMethod("*"); // 3

        return corsConfiguration;

    }

 

    @Bean

    public CorsFilter corsFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        source.registerCorsConfiguration("/**", buildConfig()); // 4

        return new CorsFilter(source);

    }

}


后来改为Filter方式


 


 


@Component

public class CorsFilter implements Filter {

 

    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);

 

 

 

    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","*");

        response.setHeader("Access-Control-Allow-Credentials", "true");

        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

        response.setHeader("Access-Control-Max-Age", "3600");

        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        chain.doFilter(req, res);

    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

 


网上很多资料都是教按以上方法设置,但是我这里就是设置不成功的。出现下面问题


 


Fetch API cannot load https://atfcapi.alpha.elenet.me/atfcapi/project/mainPageList. 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 'https://atfcapi-test.faas.elenet.me' is therefore not allowed access.

 


目前为止,不知道为什么这样配置不可以,然后改为设置单个域名,如下显示


 


        response.setHeader("Access-Control-Allow-Origin", "https://atfcapi-test.faas.elenet.me");

这样设置就成功了,但是我们有好几个环境,同一套代码,写死一个域名并解决不了问题,


 


按照很多网络文章中所说,设置多个域名如下:


 


 response.setHeader("Access-Control-Allow-Origin", "https://atfcapi-test.faas.elenet.me,https://atfcapi-test-beta.faas.elenet.me");


但是设置完以后,并不好用,出现如下错误信息:


 


 


Fetch API cannot load https://atfcapi.alpha.elenet.me/atfcapi/project/getProjects. The 'Access-Control-Allow-Origin' header contains multiple values

<span style="color:#ff6666">'https://atfcapi-test.faas.elenet.me,https://atfcapi-test-beta.faas.elenet.me', but only one is allowed. Origin 'https://atfcapi-test.faas.elenet.me' is therefore not allowed access. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.</span>


设置为以下方式也还是错误:


 


 


 response.setHeader("Access-Control-Allow-Origin", "https://atfcapi-test.faas.elenet.me");

        response.setHeader("Access-Control-Allow-Origin", "https://atfcapi-test-beta.faas.elenet.me");

 


 


 


最后采用了一种和设置为* 的方式一样的办法,代码如下:


 


@Component

public class CorsFilter implements Filter {

 

    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);

 

 

 

    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-Credentials", "true");

        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

        response.setHeader("Access-Control-Max-Age", "3600");

        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        chain.doFilter(req, res);

    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}


从request 中的header中获取Origin,来做配置,最终成功并满足需求。


  • 2018-11-17 21:08:09

    Android 单个应用的内存限制

    获取Android手机应用内存大小 手机不同其性能也不同,手机本身内存可能有大有小,所以针对每个应用的内存大小也不相同。

  • 2018-11-17 21:11:14

    Android中App可分配内存的大小

     结果:(1)未设定属性android:largeheap = "true"时,可以申请到的最大内存空间为221M。      (2)设定属性android:largeheap = "true"时, 可以申请的最大内存空间为478M,是原来的两倍多一些。

  • 2018-11-17 22:44:53

    LeakCanary,30分钟从入门到精通

    在性能优化中,内存是一个不得不聊的话题;然而内存泄漏,显示已经成为内存优化的一个重量级的方向。当前流行的内存泄漏分析工具中,不得不提的就是LeakCanary框架;这是一个集成方便, 使用便捷,配置超级简单的框架,实现的功能却是极为强大的。

  • 2018-11-17 22:53:01

    gc for alloc freed

    在数组中选择图片然后显示,然后。。。logcat不断显示GC回收。最后程序黑屏。

  • 2018-11-17 23:25:38

    Android高效内存1:一张图片占用多少内存

    在做内存优化的时候,我们发现除了解决内存泄露问题,剩下的就只有想办法减少真实的内存占用。而在App中,大部分内存可能被我们图片占用了,所以减少图片的内存占用可以带来直接的效果。本文就简单介绍一张图片到底占用多少内存,我们先假设我们有一张图片时 600 * 800 的,图片占用空间大小假设是 100KB。另外本文知识点也是面试官喜欢问的一个点,看看自己的回答到什么级别了。

  • 2018-11-18 09:06:06

    Android子线程中更新UI的3种方法

    UI的更新必须在主线程中完成,所以不管上述那种方法,都是将更新UI的消息发送到了主线程的消息对象,让主线程做处理。

  • 2018-11-19 15:10:23

    nodemailer的使用,nodejs发送邮件

    前段时间有个很普通的项目需要发邮件的功能,而且是刚开始学nodejs,所以只是搜索了下用什么好的库能实现,就找到了nodemailer了。这篇文章主要是记录一下使用的过程和经验。

  • 2018-11-21 09:07:37

    Android为每个应用分配多少内存?

    熟悉Android内存分配机制的朋友都知道,Android为每个进程分配内存时,采用弹性的分配方式,即刚开始并不会给应用分配很多的内存,而是给每一个进程分配一个“够用”的内存大小。