文件在D:\E\学习文档子目录压缩\框架\微服务相关\问题解决\跨域问题.docx
-
- 网关服务中配好路由
spring:
cloud:
gateway:
routes:
- id: admin_route
uri: lb://renren-fast
predicates:
- Path=/api/**
filters:
- RewritePath=/api(?<segment>/?.*), /renren-fast/$\{segment}
-
- 编写,允许跨域加入响应头的代码--filter
--如果跨域请求出现 OPTIONS,OPTIONS产生原因是发送真正请求前,
* 会发一个预检请求,那么我们可以写一个filter在发预检请求的时候,
* 添加响应头,允许跨域,这样在真正发请求时就可以跨域了
package com.xiangshuai.gulimall.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;
@Configuration
public class GulimallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1、配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
-
- 如果我们在网关里面的filter已经加好了请求头,那么记得将真正请求的应用的请求头去掉(如果有加的话)
@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);
// }
}
2.
2.1
2.1.1
2.1.2
2.2
2.2.1