记录一次 SpringBoot 中处理跨域
由于把shiro改造成前后台分离的Restful
风格, 启动项目,duang~~ #(不高兴)
百度 --> 经典的跨域问题
何为跨域?
Url
的一般格式:
协议
+ 域名
(子域名 + 主域名) + 端口号
+ 资源地址
示例:
https://www.dustyblog.cn:8080/say/Hello
是由
https
+ www
+ dustyblog.cn
+ 8080
+ say/Hello
组成。
只要协议,子域名,主域名,端口号这四项组成部分中有一项不同,就可以认为是不同的域,不同的域之间互相访问资源,就被称之为跨域。
只介绍 springboot 通用的解决方案
解决跨域的方法有很多种:
- 注解驱动 (
@CrossOrigin
注解) - 过滤器 或 拦截器实现 (在
response
中写入所需要的响应头) - CORS全局配置 (springboot 服务中心添加一个配置文件)
介绍下第三种方式
新建跨域配置类:CorsConfig.java
package cn.yiidii.panel.config;
import lombok.extern.slf4j.Slf4j;
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
@Slf4j
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
private CorsConfiguration buildConfig() {
log.debug("*************************CorsConfig buildConfig");
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
corsConfiguration.setAllowCredentials(true);//支持安全证书。跨域携带cookie需要配置这个
corsConfiguration.setMaxAge(3600L);//预检请求的有效期,单位为秒。设置maxage,可以避免每次都发出预检请求
return corsConfiguration;
}
}
完美解决!
转载: 天工开物_152368 - Spring Boot如何解决前端的Access-Control-Allow-Origin跨域问题