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