第一种跨域解决方式
第一种就是我们平常使用的解决跨域问题的方法,但是要实现WebMvcConfigurer 接口,还需要导入web依赖,如果我们不引入web依赖,如何解决跨域呢?
答:看第二种方式
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
CorsConfig
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author xjz_2002
* @version 1.0
*/
@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);
}
}
第二种跨域解决方式
1. config类解决跨域请求
如果我们这个微服务模块不引入web依赖,只是用来做一个网关,遇到跨域问题可以中下面代码解决
package com.xjz.xjzliving.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;
/**
* 在 gateway 统一解决跨域问题
* 不需要引入web依赖 实现去 WebMvcConfigurer接口 就可以解决跨域问题
* @author xjz_2002
* @version 1.0
*/
@Configuration
public class XjzlivingGatewayCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter() {
System.out.println("enter....");
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);
}
}
2. yml配置文件解决跨域请求:
现在的请求通过经过gateWay网关时,需要在网关统一配置跨域请求,需求所有请求通过
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowed-origins: "*"
allowed-headers: "*"
allow-credentials: true
allowed-methods:
- GET
- POST
- DELETE
- PUT
- OPTION