springboot如何配置允许跨域访问
更新时间:2024年08月09日 09:52:05 作者:L若儿
这篇文章主要介绍了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;
/**
* @author suntongxin
* Create on 2017年7月6日下午8:05:19
* All right reserved
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //允许任何域名
corsConfiguration.addAllowedHeader("*"); //允许任何头
corsConfiguration.addAllowedMethod("*"); //允许任何方法
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); //注册
return new CorsFilter(source);
}
}前后端分离跨域问题的解决
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 CorsConfig {
// 当前跨域请求最大有效时长。我设置的是一天的时间
private static final long MAX_AGE = 24 * 60 * 60;
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
return new CorsFilter(source);
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
什么是 Java 的 CyclicBarrier(代码示例)
CyclicBarrier 是多线程协同的利器,适合需要多次同步的场景,本文通过代码示例讲解什么是 Java 的 CyclicBarrier,感兴趣的朋友一起看看吧2025-03-03
解决java.lang.NoClassDefFoundError错误的问题
在Java开发过程中,NoClassDefFoundError是一个常见的运行时错误,是由于JVM在运行时找不到已编译的类文件导致的,本文就来介绍一下如何解决,具有一定的参考价值,感兴趣的可以了解一下2024-09-09
JavaWeb项目web.xml中出现Element xxx is not al
这篇文章主要介绍了JavaWeb项目web.xml中出现Element xxx is not allowed here问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-11-11


最新评论