SpringBoot轻松跨域

1.项目结构,config包下放入一个配置类 SpringBoot轻松跨域
文章图片
image.png 2.WebMvcConfigurer配置类

![image.png](https://upload-images.jianshu.io/upload_images/16112273-13fbf5da38ed6b13.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #2.WebMvcConfigurer配置类 package com.springboot.mybatis.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebMvcConfigurer extends WebMvcConfigurerAdapter { //跨域配置 @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override //重写父类提供的跨域请求处理的接口 public void addCorsMappings(CorsRegistry registry) { //添加映射路径 registry.addMapping("/**") //放行哪些原始域 .allowedOrigins("*") //是否发送Cookie信息 .allowCredentials(true) //放行哪些原始域(请求方式) .allowedMethods("GET", "POST", "PUT", "DELETE") //放行哪些原始域(头部信息) .allowedHeaders("*") //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息) .exposedHeaders("Header1", "Header2"); } }; } }

3.然后前端就可以进行跨域访问了

    推荐阅读