SpringCloud Gateway跨域配置代码实例

网友投稿 218 2022-12-21


SpringCloud Gateway跨域配置代码实例

这篇文章主要介绍了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.springhttp://framework.cloud.gateway.config.GlobalCorsProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import JHneRsWdKorg.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.regishttp://terCorsConfiguration(path, corsConfiguration));

return new CorsWebFilter(source);

}

}

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:JavaWeb项目Servlet无法访问问题解决
下一篇:SpringBoot中通过实现WebMvcConfigurer参数校验的方法示例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~