springboot处理跨域

Posted Rain_in_Summer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot处理跨域相关的知识,希望对你有一定的参考价值。


package com.summer.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * class:CorsConfiguration
 * description:
 *
 */
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedHeaders("*").allowedMethods("*").allowedOrigins("*");
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }

    private org.springframework.web.cors.CorsConfiguration buildConfig() {
        org.springframework.web.cors.CorsConfiguration corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }
}

 

以上是关于springboot处理跨域的主要内容,如果未能解决你的问题,请参考以下文章

springboot 跨域处理示例代码

Springboot处理CORS跨域请求的三种方法

SpringBoot 跨域请求处理

SpringBoot跨域小结

springboot处理跨域

SpringBoot:处理跨域请求