前后端联调出现跨域问题,springboot的解决方案

编程入门 行业动态 更新时间:2024-10-11 23:20:29

前<a href=https://www.elefans.com/category/jswz/34/1771414.html style=后端联调出现跨域问题,springboot的解决方案"/>

前后端联调出现跨域问题,springboot的解决方案

自己在前后端联调的过程中,有时候会出现跨域问题
例如:

Access to XMLHttpRequest at 'http://localhost:9090/article/categories' from origin 'http://localhost:9091' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

什么意思呢?简单点说就是请求成功发出去了,但是被拦截了,后端没收到这个请求。而且只要是端口不一致都有可能发生。

我的 springboot 项目的解决方案:

package com.feixin.config;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;@Configuration
public class CorsConfig {@Beanpublic CorsFilter corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();CorsConfiguration config = new CorsConfiguration();// 允许哪些源访问config.addAllowedOrigin("http://localhost:9091");// 允许哪些 HTTP 方法<el-menu-item>关于本站</el-menu-item>config.addAllowedMethod("*");config.addAllowedHeader("*");config.setAllowCredentials(true);source.registerCorsConfiguration("/**", config);return new CorsFilter(source);}
}

在config包下新建了一个配置类,允许该端口的所有请求访问

更多推荐

前后端联调出现跨域问题,springboot的解决方案

本文发布于:2023-11-15 19:40:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605194.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后端   解决方案   现跨域   springboot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!