springboot跨域问题 和 401
1.跨域
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;import java.util.Arrays;
import java.util.List;@Configuration
public class CorsConfig {@Value("${cors.allowed-origins}")private List<String> allowedOrigins;@Beanpublic FilterRegistrationBean<CorsFilter> corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();CorsConfiguration config = new CorsConfiguration();allowedOrigins.forEach(config::addAllowedOrigin);config.setAllowCredentials(true);config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Requested-With"));config.setMaxAge(1800L); source.registerCorsConfiguration("/**", config);FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));bean.setOrder(Ordered.HIGHEST_PRECEDENCE);return bean;}
}
application.properties
cors.allowed-origins=配置跨域放行地址 多个用 ,隔开
2. 解决跨域后 401 报错 MyWebSecurityConfiguration.java 里面 configure 添加
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
再在前端请求中添加 credentials: ‘include’, // 关键配置:携带跨域凭证 就解决了
前端请求后端 验证跨域 jsp 方式
async function callFetchRequest() {const url = "http://10.3338.33.30:344/test/test";try {const response = await fetch(url, {credentials: 'include', headers: {"Content-Type": "application/json",}});if (!response.ok) {throw new Error(`HTTP错误 ${response.status}`);}const data = await response.text();console.log("✅ 请求成功:", data);document.getElementById("result").innerText = "成功:" + data;} catch (error) {console.error("❌ 请求失败:", error);document.getElementById("result").innerText = "失败:" + error.message;}
}
在需要验证的 域名网址下面验证跨域问题 console 控制台输入这个就可以
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://10.3338.33.30:344/test/test');
xhr.withCredentials = true;
xhr.onreadystatechange = function() {if (xhr.readyState == 4 && xhr.status == 200) {console.log(xhr.responseText);}
};
xhr.send();