SpringBoot 跨域配置

SpringBoot 跨域配置介绍三种方式使用SpringBoot配置跨域。

大家好,又见面了,我是你们的朋友全栈君。

SpringBoot 跨域配置

方式一:使用过滤器

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class WebConfig { 
   

    // 过滤器跨域配置
    @Bean
    public CorsFilter corsFilter() { 
   
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();

        // 允许跨域的头部信息
        config.addAllowedHeader("*");
        // 允许跨域的方法
        config.addAllowedMethod("*");
        // 可访问的外部域
        config.addAllowedOrigin("*");
        // 需要跨域用户凭证(cookie、HTTP认证及客户端SSL证明等)
        //config.setAllowCredentials(true);
        //config.addAllowedOriginPattern("*");

        // 跨域路径配置
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

方式二:实现 WebMvcConfigurer,重写 addCorsMappings 方法

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

@Configuration
public class WebConfig implements WebMvcConfigurer { 
   

    // 拦截器跨域配置
    @Override
    public void addCorsMappings(CorsRegistry registry) { 
   
        // 跨域路径
        CorsRegistration cors = registry.addMapping("/**");

        // 可访问的外部域
        cors.allowedOrigins("*");
        // 支持跨域用户凭证
        //cors.allowCredentials(true);
        //cors.allowedOriginPatterns("*");
        // 设置 header 能携带的信息
        cors.allowedHeaders("*");
        // 支持跨域的请求方法
        cors.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
        // 设置跨域过期时间,单位为秒
        cors.maxAge(3600);
    }

    // 简写形式
    @Override
    public void addCorsMappings(CorsRegistry registry) { 
   
        registry.addMapping("/**")
                .allowedOrigins("*")
                //.allowCredentials(true)
                //.allowedOriginPatterns("*")
                .allowedHeaders("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .maxAge(3600);
    }
}

方式三:使用 @CrossOrigin 注解

@RestController
@RequestMapping("/client")
// @CrossOrigin
public class HelloController { 
   

    @CrossOrigin
    @GetMapping("/hello")
    public Result hello() { 
   
        return Result.success();
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Result test() { 
   
        return Result.fail();
    }

}
// @CrossOrigin 源码
@Target({ 
   ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin { 
   
    /** @deprecated */
    @Deprecated
    String[] DEFAULT_ORIGINS = new String[]{ 
   "*"};
    /** @deprecated */
    @Deprecated
    String[] DEFAULT_ALLOWED_HEADERS = new String[]{ 
   "*"};
    /** @deprecated */
    @Deprecated
    boolean DEFAULT_ALLOW_CREDENTIALS = false;
    /** @deprecated */
    @Deprecated
    long DEFAULT_MAX_AGE = 1800L;

    @AliasFor("origins")
    String[] value() default { 
   };

    @AliasFor("value")
    String[] origins() default { 
   };

    String[] originPatterns() default { 
   };

    String[] allowedHeaders() default { 
   };

    String[] exposedHeaders() default { 
   };

    RequestMethod[] methods() default { 
   };

    String allowCredentials() default "";

    long maxAge() default -1L;
}

vuecli+axios 测试案例

<template>
  <div class="main">
    <div class="button-group">
      <button class="button" @click="handleGet('/client/hello')">hello</button>|
      <button class="button" @click="handleGet('/client/test')">test</button>|
    </div>
  </div>
</template>

<script> import axios from '../../node_modules/axios' let http = axios.create({ 
     baseURL: 'http://localhost:9090', timeout: 1000 * 5 }) // 跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等) 这个最好是与后端的 allowCredentials 保持一致 // http.defaults.withCredentials = true export default { 
     methods: { 
     handleGet(url) { 
     http({ 
     url }).then(res => { 
     console.log(res.data) }) } } } </script>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/148580.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 使用随机函数rand()和srand()来产生三个_随机函数怎么按

    使用随机函数rand()和srand()来产生三个_随机函数怎么按srand函数是随机数发生器的初始化函数。原型:voidsrand(unsignedintseed);srand和rand()配合使用产生伪随机数序列。rand函数在产生随机数前,需要系统提供的生

    2022年8月1日
    6
  • Win10 桌面美化

    Win10 桌面美化Win10桌面美化最近发现了几款Win10界面美化的软件,看了看别人家的Win10操作界面,瞬间觉得自己的low了,关键是赏心悦目啊!废话不多说,先看看我原来桌面和美化后的桌面对比图原始桌面美化桌面1.安装RocketDockRocketDock可以提供类似macos的操作系统图标特效,打开安装包进行安装,完毕后启动得到效果如下:可以发现切换效果与mac类似,他默认的主题是C…

    2022年4月25日
    36
  • Java线程(二):线程同步synchronized和volatile

    Java线程(二):线程同步synchronized和volatile要说明线程同步问题首先要说明Java线程的两个特性,可见性和有序性。多个线程之间是不能直接传递数据交互的,它们之间的交互只能通过共享变量来实现。拿上篇博文中的例子来说明,在多个线程之间共享了Count类的一个对象,这个对象是被创建在主内存(堆内存)中,每个线程都有自己的工作内存(线程栈),工作内存存储了主内存Count对象的一个副本,当线程操作Count对象时,首先从主内存复制Co…

    2022年7月15日
    16
  • iOS在地图上WGS84、GCJ-02、BD-09互转解决方案

    iOS在地图上WGS84、GCJ-02、BD-09互转解决方案

    2022年1月10日
    41
  • WriteProcessMemory_writeandimprove

    WriteProcessMemory_writeandimproveWriteProcessMemory有好几个参数其中的nSize怎么设置??比如Short型Integer型?  nSize以字节为单位,一个字节Byte等于8位基本数据类型的长度ShortInt8位=1ByteSmallInt16位=2ByteInteger16位=2ByteLongInt32位=4ByteWord16位=2ByteLon

    2022年9月13日
    2
  • 第一课 Delphi7完全自学教程「建议收藏」

    第一课 Delphi7完全自学教程「建议收藏」   首先声明,我会以delphi7教程为主,可能会在这方面用的时间比较多,废话不多说了,今天给大家带来delphi7中最基本的面向对象程序设计语言。delphi是可视化的编程语言,delphi利用提供可视的"组件",像组件里添加一些功能或命令,该程序就有了自己所拥有的功能,比如说给组件“Button1”添加双击事件,然后干什么了?给窗体起个名字,或给按钮起一个名字都可以。这就是可视…

    2022年6月20日
    34

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号