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


相关推荐

  • SpringBoot开发常见技术整合【学习笔记整理】

    SpringBoot开发常见技术整合【学习笔记整理】

    2021年7月12日
    95
  • GitHub还是GitLab?谈谈两者的区别

    GitHub还是GitLab?谈谈两者的区别开发人员在开发编程项目时可能会面临这样一个问题,GitHub和GitLab各有优缺点,用哪一个更好呢?那么今天我们就来简单介绍一下GitHub和GitLab并谈谈它们各自的优势和短板。您真的需要用到分布式版本控制系统吗?VCS又名源代码管理(SCM)系统,旨在让开发人员、设计人员同时开发一个项目。它能够确保每个人都可以访问最新代码,并同步自己的修改。然而,这说起来容易做起来难。为了实现这一点,Linux之父LinusTorvalds发明了免费的开源分布式版本控制系统Git。Git的表现要比Ap

    2025年7月31日
    2
  • vuecli安装_离线安装vuecli

    vuecli安装_离线安装vuecli前言vue-cli是和vue进行深度组合的工具,可以快速帮我们创建vue项目,并且把一些脚手架相关的代码给我们创建好。真正使用vue开发项目,都是用vue-cli来创建项目的。vue-cli介绍

    2022年7月29日
    12
  • 缓存是什么?占内存吗?

    缓存是什么?占内存吗?

    2021年9月24日
    64
  • JAVA对象转JSON字符串时格式化日期_oracle clob转字符串

    JAVA对象转JSON字符串时格式化日期_oracle clob转字符串本案例所有代码均为原创,使用Java手写,没有借鉴其他类似工具库和网上论坛博客,也许没有经过充分测试,可能出现未知bug,因此不建议拿到正式的项目里使用。Java对象就像一个文件夹一样,没有办法知道其深度,所以采用了递归。性能方面没有测试,个人认为没有特别耗费性能的地方,除非你的对象包含很多层级。它可以支持null,字符串,数字、日期、集合等多种类型,包括以上类型的多层嵌套,都没有问题。源码不多,如下:importjava.lang.reflect.Field;importjava.lang

    2022年9月21日
    4
  • 高数——多元函数的定义及极限

    高数——多元函数的定义及极限之前我们学习的导数、微分和积分都是针对一元函数的,也就是函数只依赖一个变量,但是在我们今后遇到的实际问题中,更多出现的却是要考虑多个变量的情况,这是我们就要用多元函数来表示它们之间的关系了。比如地球表面上一点的温度T同时依赖于纬度x和经度y,可以用一个二元函数T=f(x,y)来表示。和一元函数一样,二元函数也是有定义域和值域的,一元函数的定义域是轴上一个“线段”上的点的集合,而…

    2022年6月3日
    46

发表回复

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

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