文章归档:https://www.yuque.com/u27599042/coding_star/xc80n6opewy92kfp
通过编写配置类实现 WebMvcConfigurer 接口解决跨域
在项目中增加 WebMvcConfigurer 接口的实现配置类 WebMvcConfig
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** Web MVC 配置类*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {/*** 配置解决跨域** @param corsRegistry 跨域注册对象*/@Overridepublic void addCorsMappings(CorsRegistry corsRegistry) {corsRegistry// 配置哪些请求路径允许跨域.addMapping("/**")// 是否发送 Cookie.allowCredentials(true)// 允许跨域的请求来源,设置 Access-Control-Allow-Origin.allowedOriginPatterns("*")// 允许跨域的请求方法类型.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})// 允许跨域的请求头信息,设置 Access-Control-Allow-Headers.allowedHeaders("*")// 暴露的头信息,设置 Access-Control-Expose-Headers,默认空.exposedHeaders("*");}
}