温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringCloud Gateway跨域配置代码实例

发布时间:2020-09-17 07:26:55 来源:脚本之家 阅读:575 作者:自行车上的程序员 栏目:编程语言

这篇文章主要介绍了SpringCloud Gateway跨域配置代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Springboot版本:2.1.8.RELEASE

SpringCloud版本:Greenwich.SR2

yml配置:

spring:
 cloud:
  gateway:
   globalcors:
    cors-configurations:
     '[/**]': 
      # 允许携带认证信息
      # 允许跨域的源(网站域名/ip),设置*为全部
      # 允许跨域请求里的head字段,设置*为全部
      # 允许跨域的method, 默认为GET和OPTIONS,设置*为全部
      # 跨域允许的有效期
      allow-credentials: true
      allowed-origins: 
      - "http://localhost:13009"
      - "http://localhost:13010"
      allowed-headers: "*"
      allowed-methods: 
      - OPTIONS
      - GET
      - POST
      max-age: 3600
      # 允许response的head信息
      # 默认仅允许如下6个:
      #   Cache-Control
      #   Content-Language
      #   Content-Type
      #   Expires
      #   Last-Modified
      #   Pragma
      #exposed-headers:

配置类:org.springframework.cloud.gateway.config.GlobalCorsProperties

网上有很多人说这样配无效,但我测试下来是OK的,如果真的无效,可以手动去装配Cros配置:

package com.longge.gateway.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * @author roger yang
 * @date 11/21/2019
 */
@Configuration
@ConditionalOnBean(GlobalCorsProperties.class)
public class CorsAutoConfiguration {
  @Autowired
  private GlobalCorsProperties globalCorsProperties;
  
  @Bean
  public CorsWebFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    globalCorsProperties.getCorsConfigurations().forEach((path,corsConfiguration)->source.registerCorsConfiguration(path, corsConfiguration));
    return new CorsWebFilter(source);
  }
}

当然,我们更推荐在Nginx等中间件去做跨域的处理,业务服务就应该关注业务。

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI