如何解决Spring boot 和Vue开发中CORS跨域问题

这篇文章主要介绍如何解决Spring boot 和Vue开发中CORS跨域问题,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

1. 遇到的问题:

我用spring-boot 做Rest服务,Vue做前端框架,用了element-admin-ui这个框架做后台管理。在调试的过程中遇到了如下错误:

Preflight response is not successful

2. 分析问题

这个问题是典型的CORS跨域问题。

所谓跨域:

跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。

3. 解决方法

在项目中添加类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);
  }
}

以上是“如何解决Spring boot 和Vue开发中CORS跨域问题”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!