当我们需要将spring boot以restful接口的方式对外提供服务的时候,如果此时架构是前后端分离的,那么就会涉及到跨域的问题,那怎么来解决跨域的问题了,下面就来探讨下这个问题。

解决方案一:

在Controller上添加@CrossOrigin注解

使用方式如下:

  1. @CrossOrigin // 注解方式
  2. @RestController
  3. public class HandlerScanController {
  4. @CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod.GET,
  5. RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS,
  6. RequestMethod.HEAD, RequestMethod.PUT, RequestMethod.PATCH}, origins="*")
  7. @PostMapping("/confirm")
  8. public Response handler(@RequestBody Request json){
  9. return null;
  10. }

解决方案二:全局配置

代码如下:

  1. @Configuration
  2. public class MyConfiguration {
  3. @Bean
  4. public WebMvcConfigurer corsConfigurer() {
  5. return new WebMvcConfigurerAdapter() {
  6. @Override
  7. public void addCorsMappings(CorsRegistry registry) {
  8. registry.addMapping("/**")
  9. .allowCredentials(true)
  10. .allowedMethods("GET");
  11. }
  12. };
  13. }
  14. }

解决方案三:结合Filter使用
在spring boot的主类中,增加一个CorsFilter

  1. /**
  2. *
  3. * attention:简单跨域就是GET,HEAD和POST请求,但是POST请求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
  4. * 反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次OPTIONS请求,一次真正的请求
  5. */
  6. @Bean
  7. public CorsFilter corsFilter() {
  8. final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  9. final CorsConfiguration config = new CorsConfiguration();
  10. config.setAllowCredentials(true); // 允许cookies跨域
  11. config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
  12. config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
  13. config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
  14. config.addAllowedMethod("OPTIONS");// 允许提交请求的方法,*表示全部允许
  15. config.addAllowedMethod("HEAD");
  16. config.addAllowedMethod("GET");// 允许Get的请求方法
  17. config.addAllowedMethod("PUT");
  18. config.addAllowedMethod("POST");
  19. config.addAllowedMethod("DELETE");
  20. config.addAllowedMethod("PATCH");
  21. source.registerCorsConfiguration("/**", config);
  22. return new CorsFilter(source);
  23. }

当然,如果微服务多的话,需要在每个服务的主类上都加上这么段代码,这违反了DRY原则,更好的做法是在zuul的网关层解决跨域问题,一劳永逸。

spring cloud-前端跨域问题的解决方案的更多相关文章

  1. Spring cloud zuul跨域(一)

    项目背景:我们有web和大屏,以及移动端,需要访问微服务接口. 然而大屏时自己打开的网页,在网页中通过js调用我的webapi.出现了跨域情况. 原因:出现这个问题,是由于跨域请求有2次请求. 第一次 ...

  2. Spring cloud zuul跨域(二)

    使用  CorsFilter  解决ajax跨域问题 直接在zuul的main下面,创建corsFilter就可以了. @SpringBootApplication @EnableZuulProxy ...

  3. Spring Cloud Gateway 跨域 CORS 配置方式实现

    网上找了一堆文章全是说这样写无效 globalcors: cors-configurations: '[/**]': allowCredentials: true allowedOriginPatte ...

  4. 跨域问题,解决方案-Nginx反向代理

    跨域问题,解决之道 跨域问题,在日常开发过程中,是一个非常熟悉的名词.今天的话题,结合我之前的项目场景,讨论下<跨域问题,解决之道>. 跨域是什么 跨域问题,是由于JavaScript出于 ...

  5. Ajax+Spring MVC实现跨域请求(JSONP)JSONP 跨域

    JSONP原理及实现 接下来,来实际模拟一个跨域请求的解决方案.后端为Spring MVC架构的,前端则通过Ajax进行跨域访问. 1.首先客户端需要注册一个callback(服务端通过该callba ...

  6. Ajax+Spring MVC实现跨域请求(JSONP)(转)

    背景: AJAX向后台(springmvc)发送请求,报错:已阻止交叉源请求:同源策略不允许读取 http://127.0.0.1:8080/DevInfoWeb/getJsonp 上的远程资源.可 ...

  7. Ajax+Spring MVC实现跨域请求(JSONP)

    背景: AJAX向后台(springmvc)发送请求,报错:已阻止交叉源请求:同源策略不允许读取 http://127.0.0.1:8080/DevInfoWeb/getJsonp 上的远程资源.可 ...

  8. spring @CrossOrigin解决跨域问题

    阅读目录: 一.跨域(CORS)支持: 二.使用方法: 1.controller配置CORS 2.全局CORS配置 3.XML命名空间 4.How does it work? 5.基于过滤器的CORS ...

  9. 第四节:跨域请求的解决方案和WebApi特有的处理方式

    一. 简介 前言: 跨域问题发生在Javascript发起Ajax调用,其根本原因是因为浏览器对于这种请求,所给予的权限是较低的,通常只允许调用本域中的资源, 除非目标服务器明确地告知它允许跨域调用. ...

随机推荐

  1. SDM(Supervised Descent Method and its Applications to Face Alignment )

    sdm SDM 人脸对齐的核心内容很简单,就是特征到偏移量的映射:                                           Ix = R I 是特征,x是映射矩阵,R是偏移 ...

  2. Vim 文件coding gbk格式

    只需在 ~/.vimrc设置一致即可.文件编辑可正常显示中文,cat,不能正常显示,显示乱码,详情参考上篇. set fileencodings=utf-8,ucs-bom,gb18030,gbk,g ...

  3. Linux命令学习之路——变更文档拥有者:chown

    使用权限:root用户 使用方式:chown [ -cvfRh ] [ --help ] [ --version ] user[ :group ] file... 作用:该命令用于改变文档的拥有者 注 ...

  4. Logo的制作

    <style> header { width: 1300px; height: 100px; /* background-color: pink; */ margin: 0 auto; p ...

  5. Kubernetes学习

    DNS for Services and Pods Services 创建基本的Service kind: Service spec.clusterIP: 为一组相同的服务的Pod集群提供一个虚拟ip ...

  6. Python--subprocess系统命令模块-深入

    当我们运行python的时候,我们都是在创建并运行一个进程.正如我们在Linux进程基础中介绍的那样,一个进程可以fork一个子进程,并让这个子进程exec另外一个程序.在Python中,我们通过标准 ...

  7. Go Example--缓存通道

    package main import "fmt" func main() { //缓存通道 msg := make(chan string,2) msg <- " ...

  8. 【mybatis源码学习】调试mybatis的第一个程序

    [一].基础知识准备 mybatis-config.xml配置文件的结构 MyBatis配置文件中大标签configuration下子标签包括: configuration |--- properti ...

  9. Avoiding post increase or decrease

    When we write a loop, most of us will use post increase or decrease, but there is a better solution. ...

  10. 一个License的所带来问题

    在维护一个老产品时发现一个License的问题.产品是用Z80 Z8F6423, compiler用的是ZDS II Z8 Encode! 4.9.0. 由于有一个Bug要修复,所以我重新检查了一下它 ...