Spring boot 和Vue开发中CORS跨域问题解决
跨域资源共享CORS(Cross-originResourceSharing),是W3C的一个标准,允许浏览器向跨源的服务器发起XMLHttpRequest请求,克服ajax请求只能同源使用的限制。关于CORS的详细解读,可参考阮一峰大神的博客:跨域资源共享CORS详解。
1.遇到的问题:
我用spring-boot做Rest服务,Vue做前端框架,用了element-admin-ui这个框架做后台管理。在调试的过程中遇到了如下错误:
Preflightresponseisnotsuccessful
2.分析问题
这个问题是典型的CORS跨域问题。
所谓跨域:
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。
3.解决方法
在项目中添加类CustomCORSConfiguration代码如下:
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.web.cors.CorsConfiguration;
importorg.springframework.web.cors.UrlBasedCorsConfigurationSource;
importorg.springframework.web.filter.CorsFilter;
/**
*@authorspartajet
*@description
*@create2018-05-15下午5:00
*@emailspartajet.guo@gmail.com
*/
@Configuration
publicclassCustomCORSConfiguration{
privateCorsConfigurationbuildConfig(){
CorsConfigurationcorsConfiguration=newCorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
returncorsConfiguration;
}
@Bean
publicCorsFiltercorsFilter(){
UrlBasedCorsConfigurationSourcesource=newUrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",buildConfig());
returnnewCorsFilter(source);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。