在使用vue-cli开发项目时,在本地调试程序时前端接收不到后端返回数据,并报错:
Access to XMLHttpRequest at 'http://localhost:8081/activity/list' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
createError.js?16d0:16 Uncaught (in promise) Error: Network Error
at createError (createError.js?16d0:16)
at XMLHttpRequest.handleError (xhr.js?ec6c:87)
解决办法,在后端配置http请求参数:
由于是临时的,所以直接把方法放到了application类里,注意要添加注解“@EnableScheduling”
/**
* CORS support
* @param headers
* @param methods
* @param origins
* @return
*/
@Bean
@ConditionalOnProperty(name="management.endpoints.web.cors.enable", havingValue="true")
public CorsFilter corsFilter(
@Value("${management.endpoints.web.cors.allowed-headers}") String headers,
@Value("${management.endpoints.web.cors.allowed-methods}") String methods,
@Value("${management.endpoints.web.cors.allowed-origins}") String origins) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Arrays.asList(headers.split(",")));
config.setAllowedMethods(Arrays.asList(methods.split(",")));
config.setAllowedOrigins(Arrays.asList(origins.split(",")));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
application.yml
management:
endpoints:
web:
cors:
enable: 'true'
allowed-headers: '*'
allowed-methods: '*'
allowed-origins: http://localhost:8080