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

43次阅读

共计 1543 个字符,预计需要花费 4 分钟才能阅读完成。

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

正文完
 0