gateway配置跨域

什么是跨域

浏览器同源策略:协议、域名、端口完全一致,则符合同源策略。

不符合同源策略,就会产生跨域问题。

跨域解决方案

  • 通过jsonp跨域
  • document.domain + iframe跨域
  • location.hash + iframe跨域
  • window.name + iframe跨域
  • postMessage跨域
  • 跨域资源共享 CORS
  • nginx代码跨域
  • node.js中间件代码跨域
  • WebSocket协议跨域

通常情况下,我们会选择共享资源跨域配置。

----------------------------------------------------------------------------------

跨域错误描述:

Access to XMLHttpRequest at 'https://xxx-dev-api.xx/fbp/code' from origin 'https://xxx-dev.xx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这个错误是说,origin 是https://xxx-dev.xx 的XMLHttpRequest  向 https://xxx-dev-api.xx/fbp/code 发起的请求被 cors 策略阻止了。 因为后端返回的response header里没有 Access-Control-Allow-Origin 属性。

这是前端后分离架构中,前端使用 vue框架,使用 https://xxx-dev.xx 作为域名。后端使用https://xxx-dev-api.xx 作为域名。由于同源策略,前端向后端网关发起请求时,被拒绝。

解决方案:

为后端gataway网关服务配置 共享资源跨。

网关gateway是webFlux,配置的CorsWebFilter:

@Slf4j
@Configuration
public class ResourcesConfig {

    @Bean
    public CorsWebFilter corsFilter() {

        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}

注意事项:

网关配置了跨域配置后,后端的接口不应该重复配置。重复配置后,会报错。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值