spring boot 3种方式设置跨域
标签:
SpringBoot
第一种 通过注解 @CrossOrigin(origins = "*", maxAge = 3600)
import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.RestController; @RestController@CrossOrigin(origins = "*", maxAge = 3600) public class FileController { }
第二种 Filter 方式
import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class CorsFilter implements Filter { final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class); public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT,OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
第三种 CorsConfig
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;/*** * 跨域设置 */@Configurationpublic class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } }
作者:风中吃西瓜
链接:https://www.jianshu.com/p/0d479c653bfd
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦