什么是跨域?
跨域指浏览器不能执行其他网站的脚本,可以说是与浏览器的同源策略密切相关,对浏览器来说是一种策略。同源指的是协议,域名,端口都要保持一致
例: http://www.a.com :8080 /stu
协议 域名 端口 路径
解决方案:
- JSONP(很少使用)
JSONP基于<script>标签(<script scr = " 【url+callback(回调函数名)】")></script>进行get请求跨域地址,来实现数据的加载,使其不受跨域限制,但只能支持GET请求,其他请求都不能支持。
<script src="http://aaa.com/text?callback=callbackFunction"></script>
// 向服务器aaa.com发出请求,该请求的查询字符串有一个callback参数,用来指定回调函数的名字
// 处理服务器返回回调函数的数据
<script>
function callbackFunction(res){
// 处理获得的数据
console.log(res.data)
}
</script>
- nginx反向代理(最简单) 相当于转换站
【代理服务器】
只需要修改 nginx 的配置即可解决跨域问题,支持所有浏览器,支持 session,不需要修改任何代码,并且不会影响服务器性能。
- Cros(常见)
在Springboot项目中配置文件CorsConfig.java
,重启之后即可实现跨域访问,前端无需再配置跨域。
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 {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址(* 可以设置为只允许http://localhost:8080 访问)
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}