1.定义配置类WebConfig
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 跨域配置
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
WebMvcConfigurer.super.addCorsMappings(registry);
registry.addMapping("/**") // 访问所有东西都跨域
.allowedOrigins("Http://localhost:8080","null") // 8080是前端Vue的端口号
//.allowedHeaders("*")
.allowedMethods("POST","GET","PUT","OPTIONS","DELETE") //
.maxAge(3600) // 最大响应时间
.allowCredentials(true); // 是否携带信息
}
}
如果要允许所有源跨域
把 .allowedOrigins("Http://localhost:8080","null") 改成 .allowedOriginPatterns("*")
本文介绍了如何在SpringBoot项目中使用@Configuration注解创建WebConfig类,以实现对所有资源的跨域访问,允许特定源和HTTP方法,同时支持携带凭据。
1277






