欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring cloud实现前端跨域问题的解决方案

程序员文章站 2023-12-05 16:12:04
当我们需要将spring boot以restful接口的方式对外提供服务的时候,如果此时架构是前后端分离的,那么就会涉及到跨域的问题,那怎么来解决跨域的问题了,下面就来探讨...

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

解决方案一:在controller上添加@crossorigin注解

使用方式如下:

@crossorigin // 注解方式 
@restcontroller 
public class handlerscancontroller { 
   
   
  @crossorigin(allowcredentials="true", allowedheaders="*", methods={requestmethod.get, 
      requestmethod.post, requestmethod.delete, requestmethod.options, 
      requestmethod.head, requestmethod.put, requestmethod.patch}, origins="*") 
  @postmapping("/confirm") 
  public response handler(@requestbody request json){ 
     
    return null; 
  } 
} 

解决方案二:全局配置

代码如下:

@configuration 
  public class myconfiguration { 
 
    @bean 
    public webmvcconfigurer corsconfigurer() { 
      return new webmvcconfigureradapter() { 
        @override 
        public void addcorsmappings(corsregistry registry) { 
          registry.addmapping("/**") 
          .allowcredentials(true) 
          .allowedmethods("get"); 
        } 
      }; 
    } 
  } 

解决方案三:结合filter使用

在spring boot的主类中,增加一个corsfilter 

/** 
   * 
   * attention:简单跨域就是get,head和post请求,但是post请求的"content-type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain 
   * 反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次options请求,一次真正的请求 
   */ 
  @bean 
  public corsfilter corsfilter() { 
    final urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource(); 
    final corsconfiguration config = new corsconfiguration(); 
    config.setallowcredentials(true); // 允许cookies跨域 
    config.addallowedorigin("*");// #允许向该服务器提交请求的uri,*表示全部允许,在springmvc中,如果设成*,会自动转成当前请求头中的origin 
    config.addallowedheader("*");// #允许访问的头信息,*表示全部 
    config.setmaxage(18000l);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了 
    config.addallowedmethod("options");// 允许提交请求的方法,*表示全部允许 
    config.addallowedmethod("head"); 
    config.addallowedmethod("get");// 允许get的请求方法 
    config.addallowedmethod("put"); 
    config.addallowedmethod("post"); 
    config.addallowedmethod("delete"); 
    config.addallowedmethod("patch"); 
    source.registercorsconfiguration("/**", config); 
    return new corsfilter(source); 
  } 

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

关于前端跨域的更多信息,请参考:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。