自己在前后端联调的过程中,有时候会出现跨域问题
例如:
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 {
@Bean
public 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包下新建了一个配置类,允许该端口的所有请求访问
✳
谢谢你读到这里。
更新于 2023-11-08