1.使用@CrossOrigin注解实现
 (1).对单个接口配置CORS

 @CrossOrigin(origins = {"*"})
@PostMapping("/hello")
@ResponseBody
public ResultVO hello() {
return new ResultVO(1,"成功");
}

(2).对某个Controller下的所有接口配置CORS

@CrossOrigin
@Controller
public class HelloController { }

2.配置全局的CORS

(1)添加配置类

 package com.yltx.api.config;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter; /**
* @Author: Hujh
* @Date: 2019/5/9 15:49
* @Description: Cors跨域配置
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}

(2)添加配置类

 import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /**
* @Author: Hujh
* @Date: 2019/5/9 16:18
* @Description:
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}

注:添加配置类方法取一即可.

最新文章

  1. div水平居中和垂直居中
  2. MongoDB环境准备
  3. 今天是JQ 的slideUp 和 slideDown 的点击事件
  4. 云计算和大数据时代网络技术揭秘(八)数据中心存储FCoE
  5. MySql中时间类型总结
  6. AppInventor学习笔记(五)——瓢虫快跑应用学习
  7. ligerui_实际项目_001:利用ligerLayout、ligerAccordion实现可折叠的菜单效果
  8. Your branch and 'origin/master' have diverged
  9. redis的安装-windows和linux
  10. NET/ASP.NET Routing路由(深入解析路由系统架构原理)(转载)
  11. Delphi xe7并行编程快速入门(转)
  12. linux之无名管道
  13. JOISC2019 游记
  14. python---单向循环链表实现
  15. leetCode 字符串相关问题
  16. 虚拟机安装CentOS配置静态IP
  17. 《剑指offer》-栈的压入、弹出序列
  18. 解决winfrom下TextBox不支持透明背景色
  19. 文章如何做伪原创 SEO大神教你几招做"原创"网站文章的心得
  20. WIN下Git GUI 教程

热门文章

  1. Go语言v1.8正式发布,有显著的性能提升和变化(go适合服务器编程、网络编程)
  2. 树莓派 Qt5.7交叉编译
  3. DLL中类的显式链接(用虚函数进行显式链接)
  4. 注册表Demo
  5. 关于Git GUI的使用方式
  6. 高性能高并发网站架构,教你搭建Redis5缓存集群
  7. 曹工说Tomcat3:深入理解 Tomcat Digester
  8. selenium3+python3自动化测试学习之网页元素定位
  9. Python 3网络爬虫开发实战中文 书籍软件包(原创)
  10. TypeScript算法与数据结构-数组篇