什么是跨域?
跨域就是:前端页面使用发送 AJAX 请求时,这个请求的目标地址与当前页的地址不同源。(协议、域名、端口不同)
跨域会产生什么问题?
浏览器将不会接受服务端的返回的响应。
解决方案:
1、SpringMVC中写好了CORS的跨域过滤器:CorsFilter。
增加配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
System.out.println("执行到cors过滤器");
// 1、配置CORS跨域信息
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://127.0.0.1:5500"); // 设置允许跨域的原始域名
corsConfiguration.setAllowCredentials(true); //运行携带Cookie
corsConfiguration.addAllowedMethod("*"); // 允许所有方法
corsConfiguration.addAllowedHeader("*"); // 允许所有请求头
// 2、初始化CORS配置源
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
// 3、返回CORS过滤器
return new CorsFilter(corsConfigurationSource);
}
2、重写WebMvcConfigurer类中的addCorsMappings方法
import org.springframework.context.annotation.Configuration;
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("/**")
.allowCredentials(true) //是否发送Cookie
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}