已解决
前后端联调出现跨域问题,springboot的解决方案
来自网友在路上 167867提问 提问时间:2023-11-09 20:07:11阅读次数: 67
最佳答案 问答题库678位专家为你答疑解惑
自己在前后端联调的过程中,有时候会出现跨域问题
例如:
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包下新建了一个配置类,允许该端口的所有请求访问
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"前后端联调出现跨域问题,springboot的解决方案":http://eshow365.cn/6-36494-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!