CORS 跨域简述 spring cloud gateway

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值