springboot2.7.18配置跨域
一.springboot整合security后一般要配置security的跨域和mvc的跨域才能实现跨域
1.spring-security配置跨域
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable().cors();
return http.build();
}
2.springmvc配置跨域
@Configuration
public class CorWebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.allowedHeaders("*")
.maxAge(3600);
}
}
二.测试服务器跨域
在谷歌浏览器随便打开一个网页,然后打开开发者工具的console输入下面脚本,来测试
var xhr = new XMLHttpRequest();
xhr.open('GET', '服务器地址');
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
三.如果没有在springboot上配置跨域,那么nginx上也可以配置跨域
nignx 设置跨域问题
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' '*';
# OPTIONS 直接返回204
if ($request_method = 'OPTIONS') {
return 204;}
浙公网安备 33010602011771号