spring Cloud微服務(wù)跨域?qū)崿F(xiàn)步驟
這篇文章主要介紹了spring Cloud微服務(wù)跨域?qū)崿F(xiàn)步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
第一步:在gateway網(wǎng)關(guān)的配置文件中加上下面這些:
ly: cors: allowedOrigins: - http://manage.leyou.com - http://xxx.xxx.com # 允許哪些網(wǎng)址就繼續(xù)加,不要寫 *,否則cookie就無法使用了 allowedCredentials: true # 代表攜帶cookie allowedHeaders: - "*" allowedMethods: - GET - POST - DELETE - PUT - OPTIONS - HEAD maxAge: 360000 filterPath: "/**"
第二步:寫一個配置類解析上面的配置文件信息
@Data
@ConfigurationProperties(prefix = "ly.cors")
public class CORSProperties {
private List<String> allowedOrigins;
private Boolean allowedCredentials;
private List<String> allowedMethods;
private List<String> allowedHeaders;
private long maxAge;
private String filterPath;
}
第三步:寫一個跨域的過濾器
@Configuration
@EnableConfigurationProperties(CORSProperties.class)
public class GlobalCORSConfig {
@Autowired
private CORSProperties prop;
/**
* @Bean注解,將當(dāng)前方法的返回值對象放入到IOC容器中
* @return
*/
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
prop.getAllowedOrigins().forEach(config::addAllowedOrigin);
//上面的寫法和下面這個效果一樣
// for (String allowedOrigin : prop.getAllowedOrigins()) {
// config.addAllowedOrigin(allowedOrigin);
// }
//2) 是否發(fā)送Cookie信息
config.setAllowCredentials(prop.getAllowedCredentials());
//3) 允許的請求方式
prop.getAllowedMethods().forEach(config::addAllowedMethod);
// 4)允許的頭信息
prop.getAllowedHeaders().forEach(config::addAllowedHeader);
// 5)有效期
config.setMaxAge(prop.getMaxAge());
//2.添加映射路徑,我們攔截一切請求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration(prop.getFilterPath(), config);
//3.返回新的CORSFilter.
return new CorsFilter(configSource);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
PropertiesLoaderUtils 出現(xiàn)中文亂碼的解決方式
這篇文章主要介紹了PropertiesLoaderUtils 出現(xiàn)中文亂碼的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
Java long 轉(zhuǎn)成 String的實現(xiàn)
這篇文章主要介紹了Java long 轉(zhuǎn)成 String的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
SpringBoot使用MyBatis-Flex實現(xiàn)靈活的數(shù)據(jù)庫訪問
MyBatisFlex是一款優(yōu)秀的持久層框架,本文主要介紹了SpringBoot使用MyBatis-Flex實現(xiàn)靈活的數(shù)據(jù)庫訪問,具有一定的參考價值,感興趣的可以了解一下2024-06-06
SpringMVC集成Web與MVC執(zhí)行流程和數(shù)據(jù)響應(yīng)及交互相關(guān)介紹全面總結(jié)
Spring MVC 是 Spring 提供的一個基于 MVC 設(shè)計模式的輕量級 Web 開發(fā)框架,本質(zhì)上相當(dāng)于 Servlet,Spring MVC 角色劃分清晰,分工明細,這篇文章主要介紹了SpringMVC集成Web與MVC執(zhí)行流程和數(shù)據(jù)響應(yīng)及交互2022-10-10

