springboot跨域问题 和 401

发布于:2025-07-20 ⋅ 阅读:(15) ⋅ 点赞:(0)

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;

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        // 动态注入允许的Origin
        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); // 预检请求缓存30分钟

        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() // 允许所有OPTIONS预检请求

再在前端请求中添加 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; // 关键配置:携带跨域凭证[1][2][3][6]
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
};
xhr.send();

网站公告

今日签到

点亮在社区的每一天
去签到