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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • android declare-styleable 和style,Android 关于declare-styleable属性的写法….

    android declare-styleable 和style,Android 关于declare-styleable属性的写法….我想问自定义View的时候,以下这段代码,为何要写两次一样的名称呢?我看了一些资料,说写在declare-styleable系统会自动生成数组…..我不太明白这实际应用是什么?如果说自动帮你生成了数组,方便使用,那写在外面的三个又有什么作用?能从实际应用中讲一讲吗?<?xmlversion=”1.0″encoding=”utf-8″?><resources><at…

    2022年7月13日
    16
  • 整除的尾数_整除数

    整除的尾数_整除数整除的尾数时间限制:1000 ms | 内存限制:65535 KB难度:0描述一个整数,只知道前几位,不知道末二位,被另一个整数除尽了,那么该数的末二位该是什么呢?输入输入数据有若干组,每组数据包含二个整数a,b(0输出对应每组数据,将满足条件的所有尾数在一行内输出,格式见样本输出。同组数据的输出,其每个尾数之间空一格,行末没有空格。样例输入

    2025年5月24日
    2
  • Python 反转字符串_python输出字符串

    Python 反转字符串_python输出字符串python字符串反转方法Helloeveryone,inthistutorialwe’llseedifferentwaystoreversestringinPython.大家好,在本教程中,我们将看到在Python中反转字符串的不同方法。Asweknow,wecanreversealistusingreverse()methodbutPy…

    2025年8月2日
    5
  • android listview单击事件

    android listview单击事件今天我们来学习下listview单击事件,这在开发中是经常用的组件之一。1.新建一个项目,名为ListViewDemo。2.布置布局文件main.xmlandroid:orientation=”vertical”android:layout_width=”fill_parent”android:layout_height=”fill_parent”>

    2022年7月22日
    11
  • Android MVP+RxJava+Retrofit (2) RxJava+Retrofit

    Android MVP+RxJava+Retrofit (2) RxJava+Retrofit

    2021年3月12日
    146
  • 光流法小结[通俗易懂]

    光流法小结[通俗易懂]1.定义空间运动物体在观察成像平面上的像素运动的瞬时速度,是利用图像序列中像素在时间域上的变化以及相邻帧之间的相关性来找到上一帧跟当前帧之间存在的对应关系,从而计算出相邻帧之间物体的运动信息的一种方法。也就是说,由空间域到图像平面的投影。而通俗来讲,把图像中的每一个点的瞬时速度和方向找出来就是光流。2.光流有什么用通过光流判断物体距离我们的远近。一般而言,远景的物体相对来说光流较小,而近景物体

    2022年7月23日
    11

发表回复

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

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