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


相关推荐

  • EnableEventValidation启用事件验证

    EnableEventValidation启用事件验证根据出错页面给出的提示消息可以知道,默认情况下是启用了事件验证的,在Aspx页HTML部分的Page指令处添加如下属性,就可以在页面回发时禁用事件验证<%@PageLanguage=”C#”EnableEventValidation=”false”.%>分析:出现这个错误一般是因为在客户端调用了js代码,改写了页面控件中的值,而通过postback再次requ…

    2022年7月24日
    13
  • dataset数据集有哪些_数据集类型

    dataset数据集有哪些_数据集类型datasets数据集​ 分享一些学习到的知识​ sklearn的数据集库datasets提供很多不同的数据集,主要包含以下几大类:玩具数据集真实世界中的数据集样本生成器样本图片svmlight或libsvm格式的数据从openml.org下载的数据从外部加载的数据用的比较多的就是1和3,这里进行主要介绍,其他的会进行简单介绍,但是不建议使用。玩具数据集​ scikit-learn内置有一些小型标准数据集,不需要从某个外部网站下载任何文件,用

    2022年4月19日
    190
  • 原型和原型链理解_原型对象和原型链

    原型和原型链理解_原型对象和原型链一、原型①所有引用类型都有一个__proto__(隐式原型)属性,属性值是一个普通的对象②所有函数都有一个prototype(原型)属性,属性值是一个普通的对象③所有引用类型的__proto__属性指向它构造函数的prototypevara=[1,2,3];a.__proto__===Array.prototype;//true二、原型链…

    2025年7月26日
    7
  • 如何使用手机免费将PDF转Word还不限页数

    如何使用手机免费将PDF转Word还不限页数手机如何将PDF转换成Word?有时一些PDF资料需要修改才能使用,电脑端的修改已经很复杂了,更何况手机端安装软件和使用都更困难,而且有一些PDF文档本身就是扫描版无法进行修改,那么我们就只能将PDF转成Word后再编辑。目前一些能搜索的免费转换工具大多都付费,就算免费使用的也是很多限制,比如只能转换前3页或前5页,那么如何免费将手机里的PDF转换成Word还不限制页数呢?下面分享一个简单好用的方法,只需要三步就能轻松完成转换。第一步,首先打开手机的浏览器,输入speedpdf进行搜索,一般搜索结果第一

    2022年4月29日
    103
  • apache ant安装和build.xml

    apache ant安装和build.xml

    2021年8月13日
    76
  • Java“魔法”-jstack命令解析

    怕什么真理无穷进一步有近一步的欢喜前情预告在介绍jstack之前,先简单介绍一下jps。因为jps使用相对简单,各位看官看一下便知。jps的作用是显示当前系统的java进程情况,及其id号…

    2022年3月1日
    41

发表回复

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

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