我用spring-boot
作Rest
服務,Vue
作前端框架,用了element-admin-ui
這個框架作後臺管理。在調試的過程當中遇到了以下錯誤:前端
Preflight response is not successful
這個問題是典型的CORS
跨域問題。web
所謂跨域:spring
跨域,指的是瀏覽器不能執行其餘網站的腳本。它是由瀏覽器的同源策略形成的,是瀏覽器對JavaScript施加的安全限制。
在項目中添加類CustomCORSConfiguration
代碼以下:跨域
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; /** * @author spartajet * @description * @create 2018-05-15 下午5:00 * @email spartajet.guo@gmail.com */ @Configuration public class CustomCORSConfiguration { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setAllowCredentials(true); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } }