跨域问题:
浏览器禁止请求的发起者与服务端发生跨域ajax请求,请求被浏览器拦截的问题
解决方案:CORS,这个以前应该学习过,这里不再赘述了。
不知道的小伙伴可以查看跨域资源共享 CORS 详解 - 阮一峰的网络日志
解决跨域问题
方式一:在gateway服务的application.yml文件中,添加下面的配置:
spring:
cloud:
gateway:
# 。。。
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]': # 所有的请求都要走以下策略
allowedOrigins: # 允许哪些网站的跨域请求
- "http://localhost"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期(单位:秒)
方式二:用代码方式解决跨域
package com.itheima.gateway.config;
import lombok.extern.slf4j.Slf4j;
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;
@Slf4j
@Configuration
public class WebSecurityConfig {
@Bean
public CorsWebFilter corsFilter() {
log.info("cors跨域处理...");
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 是否允许携带cookie
config.addAllowedOrigin("*"); // 可接受的域,是一个具体域名或者*(代表任意域名)
config.addAllowedHeader("*"); // 允许携带的头
config.addAllowedMethod("*"); // 允许访问的方式
// 基于Url的跨域配置
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 针对所有的请求Url,采用上面的Config配置
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}