Quellcode durchsuchen

跨域问题解决

gaodm vor 5 Jahren
Ursprung
Commit
9729e460d0

+ 30 - 0
src/main/java/com/diagbot/config/CorsConfiguer.java

@@ -0,0 +1,30 @@
+package com.diagbot.config;
+
+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;
+
+/**
+ * @Description:
+ * @author: gaodm
+ * @time: 2020/4/12 15:56
+ */
+@Configuration
+public class CorsConfiguer {
+    private CorsConfiguration buildConfig() {
+        CorsConfiguration corsConfiguration = new CorsConfiguration();
+        corsConfiguration.addAllowedOrigin("*"); // 允许的域名
+        corsConfiguration.addAllowedHeader("*"); // 允许的请求头
+        corsConfiguration.addAllowedMethod("*"); // 允许的方法(post、get等)
+        return corsConfiguration;
+    }
+
+    @Bean
+    public CorsFilter corsFilter() {
+        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+        source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
+        return new CorsFilter(source);
+    }
+}

+ 2 - 1
src/main/java/com/diagbot/config/ResourceServerConfigurer.java

@@ -23,7 +23,8 @@ public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
 
     @Override
     public void configure(HttpSecurity http) throws Exception {
-        http
+        http.cors()
+                .and()
                 .csrf().disable()
                 .authorizeRequests()
                 .regexMatchers(".*swagger.*", ".*v2.*", ".*webjars.*", "/druid.*", "/actuator.*", "/hystrix.*").permitAll()