使用gateway网关解决浏览器跨域问题,源码解析

跨域:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。
我们这里利用CORS策略,对我们的网关进行修改,让他接收到跨域请求的时候忽略掉OPTION中的报头不同。
这里我们创建个config包,来装跨域配置在这里插入图片描述
spirngbot配置中在CorsWebFilter设置了跨域问题,我们只需要写一个方法覆盖他即可,翻看源码我们可以发现他需要两个类,一个是CorsConfigurationSource还有一个是CorsProcessor,而CorsConfigurationSource是个接口,他的实现类是UrlBasedCorsConfigurationSource,我们要配置的就是它
在这里插入图片描述

package com.zsp.zspmall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Configuration
public class ZspMallCorsConfig {
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}


corsConfiguration.addAllowedHeader(""); :允许所有请求头
corsConfiguration.addAllowedMethod("
"); :允许所有请求方法,例如get,post等
corsConfiguration.addAllowedOrigin("*");允许所有的请求来源
corsConfiguration.setAllowCredentials(true); 允许携带cookie
source.registerCorsConfiguration("/**",corsConfiguration); 对所有经过网关的请求都生效
看不懂也没事,直接把这个粘到你的配置类里即可。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值