关于springboot:springboot跨域问题-HTTP访问控制CORS

1.谬误形容

其实就还是我上个guacamole我的项目的衍生问题,因为要提供一个供外界拜访的接口,以后端页面填入我在其余服务器上安排的guacamole server的地址的时候(我用的firefox浏览器)在控制台能够分明地看到

CORS 头短少 ‘Access-Control-Allow-Origin’

这些字样

2.解决

这里先上解决办法,试了好多种只有这个能够

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


@Configuration
public class GlobalCorsConfig extends WebMvcConfigurerAdapter {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addExposedHeader("Content-Type");
        corsConfiguration.addExposedHeader( "X-Requested-With");
        corsConfiguration.addExposedHeader("accept");
        corsConfiguration.addExposedHeader("Origin");
        corsConfiguration.addExposedHeader( "Access-Control-Request-Method");
        corsConfiguration.addExposedHeader("Access-Control-Request-Headers");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

创立这个类,而后在须要进行跨域的类下面加上注解@CrossOrigin
跨域问题就解决了!具体原理我还没了解,了解了补上,这里贴一下帮我解决问题的网址:https://www.w3xue.com/exp/article/20193/23459.html

评论

发表回复

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

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理