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


慕飞烟
5 声望0 粉丝

如果你听到一个人抖腿的声音并且很烦的时候,那么请发出和他相同频率的声音,你会控制他