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

作者:青春无罪 时间:2024-04-28 09:32:54 

跨域资源共享CORS(Cross-origin Resource Sharing),是W3C的一个标准,允许浏览器向跨源的服务器发起XMLHttpRequest请求,克服ajax请求只能同源使用的限制。关于CORS的详细解读,可参考阮一峰大神的博客:跨域资源共享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);
 }
}

来源:https://segmentfault.com/a/1190000016258859

标签:Springboot,Vue,跨域
0
投稿

猜你喜欢

  • python基础教程项目五之虚拟茶话会

    2022-10-25 02:08:47
  • TypeScript工具类 Partial 和 Required 的场景分析

    2024-04-29 13:14:45
  • Python无法用requests获取网页源码的解决方法

    2023-04-24 07:38:04
  • Go语言高效编程的3个技巧总结

    2024-02-03 02:52:38
  • Python 读取某个目录下所有的文件实例

    2022-08-27 20:04:13
  • Python 实现图片转字符画的示例(静态图片,gif皆可)

    2023-04-11 13:42:38
  • Langchain集成管理prompt功能详解

    2022-12-13 22:56:31
  • Python中模块pymysql查询结果后如何获取字段列表

    2023-07-23 18:52:54
  • Python3 解释器的实现

    2023-08-09 17:08:53
  • Python 字符串转换为整形和浮点类型的方法

    2021-09-02 00:09:31
  • Pyqt+matplotlib 实现实时画图案例

    2022-01-06 12:52:23
  • Javascript世界的最大整数值

    2008-06-23 13:23:00
  • PHP异常Parse error: syntax error, unexpected T_VAR错误解决方法

    2023-11-16 13:00:48
  • python3.7添加dlib模块的方法

    2023-09-16 03:58:55
  • Vue+Antv F2实现层叠柱状图

    2023-07-02 16:54:55
  • jquery中文手册上的一点错误--说说p标签失去焦点

    2009-09-13 21:24:00
  • SQL语句练习实例之五 WMS系统中的关于LIFO或FIFO的问题分析

    2024-01-16 06:47:26
  • 解决django的template中如果无法引用MEDIA_URL问题

    2023-06-12 15:09:07
  • SQL中distinct 和 row_number() over() 的区别及用法

    2024-01-12 20:16:35
  • 百度的图片轮换JS代码,支持FF

    2007-11-16 16:24:00
  • asp之家 网络编程 m.aspxhome.com