Spring Boot中解决跨域问题(CORS)

编程入门 行业动态 更新时间:2024-10-24 09:20:30

<a href=https://www.elefans.com/category/jswz/34/1769862.html style=Spring Boot中解决跨域问题(CORS)"/>

Spring Boot中解决跨域问题(CORS)

1. 跨域介绍

首先解释什么是跨域,跨域就是前端和后端的端口号不同;会产生跨域问题,这里浏览器的保护机制(同源策略)。
同源策略:前端和后端的协议、域名、端口号三者都相同叫做同源。
我们看一下不同源:
VUE:http://localhost:8080
Spring: http://localhost:8081/list
当我们出现跨域问题,前端就会报一个错(篮框扩这那个):

2. 解决方法

上方就是不同源,两者的协议、域名相同,但是端口号不同;如何解决呢,使用Spring Boot解决,它提供三种方案:

  1. 直接在方法上方添加@CrossOrigin注解即可解决问题
	@CrossOrigin@RequestMapping("/getuserbyid")public UserInfo getUserById(Integer id) {if(id == null ) return null;return userService.getUserById(id);}
  1. 添加 CORS 过滤器
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;@Configuration
public class CorsConfig {@Beanpublic CorsFilter corsFilter() {CorsConfiguration corsConfiguration = new CorsConfiguration();corsConfiguration.setAllowCredentials(true); // 允许cookies跨域corsConfiguration.addAllowedHeader("*"); // 请求头字段corsConfiguration.addAllowedMethod("*"); // 方法corsConfiguration.addAllowedOrigin("*"); // 允许向该服务器提交请求的URI,*表示全部允许,自定义可以添加多个,在SpringMVC中,如果设成*,会自动转成当前请求头中的OriginUrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**",corsConfiguration); // 添加映射路径,以及参数return new CorsFilter(source);}
}
  1. 重写 WebMvcConfigurer 接口中的 addCorsMappings 方法
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {// 先设置映射registry.addMapping("/**").allowedOriginPatterns("*") // 允许向该服务器提交请求的URI,*表示全部允许,自定义可以添加多个,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin.allowCredentials(true) // 允许cookies跨域.allowedHeaders("*") // 请求头字段.allowedMethods("GET","POST") // 允许跨域的方法.maxAge(3600);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了}
}

更多推荐

Spring Boot中解决跨域问题(CORS)

本文发布于:2023-11-17 00:00:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634701.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Spring   Boot   CORS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!