springboot解决接口跨域问题
CorsConfig跨域配置类一
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;
import java.util.Arrays;
/** * @author junqi.pi */
@Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 允许所有域名跨域 config.setAllowedOrigins(Arrays.asList("*")); // 允许所有请求头 config.setAllowedHeaders(Arrays.asList("*")); // 允许所有方法 config.setAllowedMethods(Arrays.asList("*")); config.setMaxAge(300L); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
CorsConfig跨域配置类二
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author junqi.pi */ @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("*") .maxAge(1728000); } }
选择一种当成工具类直接添加进项目里就行了
但是这种方法是允许所有的跨域请求 有一定的安全性问题 后期再优化 请谨慎选择
本文来自博客园,作者:皮军旗,转载请注明原文链接:https://www.cnblogs.com/pijunqi/p/14154044.html