springboot如何解决跨域问题(4种方式)

目录

@CrossOrigin 

WebMvcConfigurer 

Filter

Nginx


@CrossOrigin 

方法上加@CrossOrigin注解即可

查看源码就显而易见了 

 但是在多模块 多控制器 多个方法下 会显得代码冗余 不推荐用它到项目的每一个地方

WebMvcConfigurer 

实现WebMvcConfigurer接口 重写addCorsMappings()方法即可

@Configuration
public class CORSWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //添加映射路径
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
                //设置放行哪些原始域   SpringBoot2.4.4下低版本使用.allowedOrigins("*")
                .allowedOriginPatterns("*")
                //放行哪些请求方式
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                //.allowedMethods("*") //或者放行全部
                //放行哪些原始请求头部信息
                .allowedHeaders("*")
                //暴露哪些原始请求头部信息
                .exposedHeaders("*");
    }

注意springboot的版本(2.2.4以下使用alloweOrigins() 以上使用allowedOrginPatterns())

Filter

不需要注册,直接使用springboot提供的 CrosFilter

import org.springframework.web.filter.CorsFilter;
@Configuration
public class CORSWebFilter {
    @Bean
   public CorsFilter corsFilter(){
        CorsConfiguration config = new CorsConfiguration();
        // 允许跨域的头部信息
        config.addAllowedHeader("*");
        // 允许跨域的方法
        config.addAllowedMethod("*");
        // 可访问的外部域
        config.addAllowedOrigin("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        CorsFilter corsFilter = new CorsFilter(source);
        return corsFilter;
    }

Nginx

指令

nginx.exe 启动nginx

nginx.exe -s stop 停止nginx

ngin -s reload 重启nginx

netstat -ano | findstr 80 产看是否被占用了

taskkill -pid xxx   如果是的就kill掉

在  location / {} 里面直接添加这段代码即可

            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
            add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
          if ($request_method = 'OPTIONS') {
              return 204;
          }
         #进行反向代理
          proxy_pass http://localhost:[你的端口]/[方法路劲];

Nginx做跨域处理的好处就是完全不用在后端或者前端代码 更能体现架构上的分离

需要注意的是

  1. 你必须可以访问localhost:80 看到nginx默认的首页
  2. 修改好配置文件(nginx.conf)需要重启Nginx加载配置(nginx.exe -s reload即可)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值