SpringBoot轻松跨域
1.项目结构,config包下放入一个配置类
文章图片
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.然后前端就可以进行跨域访问了
推荐阅读
- Activiti(一)SpringBoot2集成Activiti6
- SpringBoot调用公共模块的自定义注解失效的解决
- 解决SpringBoot引用别的模块无法注入的问题
- 松软可口易消化,无需烤箱超简单,新手麻麻也能轻松成功~
- springboot使用redis缓存
- 川藏骑行D17:鲁朗—八一
- springboot整合数据库连接池-->druid
- 第六波财富,抓住机会轻松实现月薪过万
- SpringBoot中YAML语法及几个注意点说明
- springboot结合redis实现搜索栏热搜功能及文字过滤