最近用Axios做get请求时发现前台报
XMLHttpRequest cannot load http://127.0.0.1:8080/sayHello. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8010' is therefore not allowed access.
我这边是用SpringBoot做的后台
只需在代码里加入这个配置就可以解决SpringBoot跨域的问题
package com.rong.demo.common.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;
@Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1 corsConfiguration.addAllowedHeader("*"); // 2 corsConfiguration.addAllowedMethod("*"); // 3 return corsConfiguration; }
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/\*\*", buildConfig()); // 4
return new CorsFilter(source);
}
}