相较于前端实现跨域,有时会出现跨域失败,列举后端三种方式实现跨域
1.加注解 代码重复
- /**
- * 获取用户信息
- *
- * @return 用户信息
- */
- @GetMapping("getInfo")
- @CrossOrigin
- public AjaxResult getInfo()
- {
- SysUser user = SecurityUtils.getLoginUser().getUser();
- // 角色集合
- Set
roles = permissionService.getRolePermission(user); - // 权限集合
- Set
permissions = permissionService.getMenuPermission(user); - AjaxResult ajax = AjaxResult.success();
- ajax.put("user", user);
- ajax.put("roles", roles);
- ajax.put("permiss", permiss);
- return ajax;
- }
2.实现接口并重写方法来解决跨域
- @Configuration
- public class CORSConfiguration implements WebMvcConfigurer {
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/**")
- .allowedOriginPatterns("*")
- .allowedMethods("GET","POST","PUT","HEAD")
- .allowCredentials(true)
- .allowedHeaders("*")
- .maxAge(3600);
- }
- }
3.添加过滤器来实现跨域
- @Configuration
- public class CORSFilter {
- @Bean
- public CorsFilter corsFilter(){
- CorsConfiguration corsConfiguration = new CorsConfiguration();
- corsConfiguration.addAllowedHeader("*");
- corsConfiguration.addAllowedOrigin("*");
- corsConfiguration.addAllowedMethod("*");
- UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
- source.registerCorsConfiguration("/**",corsConfiguration);
- return new CorsFilter(source);
- }
- }