跨域一共有两张方式处理,一个是配置文件,一个是配置类
先来说配置类
1.配置类
这是配置类,cors跨域的配置,直接粘贴复制自己改改就行,如果里面有一直报红不消的话,那是cors提供的跨域配置依赖版本问题
package com.**.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("**")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 配置跨域
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许哪个请求头
corsConfiguration.addAllowedHeader("*");
// 允许哪个方法进行跨域
corsConfiguration.addAllowedMethod("*");
// 允许哪个请求来源进行跨域
// corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedOriginPattern("*");
// 是否允许携带cookie进行跨域
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
2.配置文件
配置文件就是直接粘贴就好了
spring:
cloud:
gateway:
globalcors: #全局跨越处理
add-to-simple-url-handler-mapping: true #解决options请求被拦截问题
cors-configurations:
'[/**]': #拦截所有
allowCredentials: true
#allowedOrigins: "*"#允许哪些网址跨域
allowedHeaders: "*" #允许在请求中添加头信息
allowedOriginPatterns: "*" #是否允许跨域携带cookie
maxAge: 36000 #这次跨域检测的有效期,期间内不需要再检测跨域
allowedMethods: #允许跨域ajax的请求方式
- "GET"
- "POST"
- "PUT"
- "DELETE"
discovery:
locator:
lowerCaseServiceId: true
enabled: true
就可以了