关于跨域那点事

1、直接上注解:@CrossOrigin  //在controller类上添加此注解

直接在需要跨域的Controller的类上添加 @CrossOrigin 跨域注解即可。

2、服务中的 CorsFilter ,这个 spring webmvc 中给出过滤器层面的跨域

  当一个模块中controlller过多时,添加注解过于繁琐,可以创建一个配置类对象,进行跨域设置,'' FilterRegistrationBean<Corsfilter> ''。

package com.example.gupan.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//标注这个类是一个配置类
@Configuration
//实现 WebMvcConfigurer 接口
public class CorsWebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")  //设置允许跨域访问的路径
                .allowedOriginPatterns("*")  //设置允许跨域访问的源
                .allowedMethods("POST", "GET")  //允许跨域请求的方法
                .maxAge(168000)  //预检间隔时间
                .allowedHeaders("*")  //允许头部设置
                .allowCredentials(true);  //是否发送 cookie
    }
}

3、网关中的CorsWebFilter ,这个是spring webflux中的过滤器

 一个网关管理多个服务时,设置此配置类对象,可以从网关层面解决多个服务的跨域问题,这就不需要每个服务都写一遍跨域了。

package com.example.gupan.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 CorsFilterConfig {

    @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);
    }
}

 注:关于此处配置后报错:

 主要就是缺少了下面的依赖,添加之后就OK了

<!--        引入 Webflux 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

4、通过 配置文件 进行跨域设置(微服务项目下推荐使用此方法)

此方法在微服务项目下可以配置到nacos等配置中心, 未来项目发布后能更灵活的处理各种请求。

spring:
  cloud:
    gateway:
      globalcors: #跨域配置
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowedMethods: "*"
            allowCredentials: true

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值