0
点赞
收藏
分享

微信扫一扫

#yyds干货盘点# SpringBoot解决跨域问题

SpringBoot解决跨域问题

创建一个filter解决跨域。

xxxxxxxxxx

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

基于WebMvcConfigurerAdapter配置加入Cors的跨域

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 CorsConfig extends WebMvcConfigurerAdapter {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
addMapping-----指哪些接口URL需要增加跨域设置

allowedOrigins-----指的是前端哪些域名被允许跨域

allowedMethods-----指的是允许哪些方法

allowCredentials----因为自己项目需要带cookie等凭证,

使用注解@CrossOrigin(局部跨域)

@Controller
@RequestMapping("/shop")
@CrossOrigin()
public class ShopController {

@GetMapping("/")
@ResponseBody
public Map<String, Object> findAll() {
//返回数据
return DataSchool.getStudents();
}
}

其中@CrossOrigin中的2个参数:

origins  : 允许可访问的域列表

maxAge:准备响应前的缓存持续的最大时间(以秒为单位)。

methods:请求的方法类型


第一种Filter的方案也支持springmvc。

第二、三种常用于springboot。



举报

相关推荐

0 条评论