1. 跨域是什么
- 跨域是指浏览器不能执行其他网站的脚本。它是浏览器同源策略造成的,是浏览器对JS实施的安全限制。
- 跨域:协议/主机/端口号,这三个条件其中一个不一样,就属于跨域。
- 重点:跨域只会出现在前端,是浏览器报错
2. 使用 Chrome 谷歌浏览器,模拟发送get / post请求
- F12打开Console输入以下代码
- 在 http://localhost:8185 页面,通过console发送http://localhost:8443/xxx/xxx/xxx/login请求,违反同源策略,浏览器报跨域错误
- 代码如下
var url = "http://localhost:8443/xxx/xxx/xxx/login";
var params = {"account":"xxx","password":"xxx"};
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.send(JSON.stringify(params));
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
3. spring cloud gateway跨域配置CORS Configuration
- 常见的gateway网关服务会进行跨域配置
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", buildConfig());
return new CorsWebFilter(source);
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//在生产环境上最好指定域名,以免产生跨域安全问题
corsConfiguration.addAllowedOrigin("http://localhost:8185");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(3600L);
return corsConfiguration;
}
}
- 跨域并不会阻止请求的发出,也不会阻止请求的接受,跨域是浏览器为了保护当前页面,你的请求得到了响应,浏览器不会把响应的数据交给页面上的回调,取而代之的是去提示你这是一个跨域数据。
- 通过Access-Control-Allow-Origin响应头,就告诉了浏览器。如果请求我的资源的页面是我这个响应头里记录了的"源",则不要拦截此响应,允许数据通行。
参考文档
https://blog.csdn.net/cmmsgwcpd/article/details/126655052
https://blog.csdn.net/m0_73414953/article/details/131071201
https://blog.csdn.net/qq_34402069/article/details/124757399