SpringBoot添加允许跨域(15)

因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;

/**

*

* Create on 

* 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);

}

}

精细配置

在需要跨域的整个Controller或者单个方法上添加@CrossOrigin注解

 

posted @ 2021-03-31 18:02  hzy_叶子  阅读(77)  评论(0编辑  收藏  举报