当前位置: 首页 > news >正文

springboot跨域问题 和 401

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();// 动态注入允许的OriginallowedOrigins.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();
http://www.lryc.cn/news/591328.html

相关文章:

  • 解锁数据分析:从基础概念到核心指标的全面指南
  • 数据分析:从数据到决策的核心逻辑与实践指南
  • 电脑DLL错误修复dll微软运行库工具修复dll缺失找不到dll等问题,dll免费修复工具
  • Servlet概述
  • 基于arduino单片机汽车智能电子防碰撞装置设计
  • linux_线程同步
  • 一文掌握Harbor的配额管理和GC机制
  • 2025测绘程序设计国赛实战 | 泰森多边形算法C#实现
  • 华为云容器产品分析
  • tcp/udp调试工具
  • Python20 —— 二维数据的处理
  • 【C++类和对象解密】面向对象编程的核心概念(下)
  • Python 网络爬虫 —— 代理服务器
  • HTML前端性能优化完整指南
  • LeetCode 234:回文链表
  • Day04_C语言网络编程20250716_sql语言大全
  • Ollama使用指南-更改默认安装路径和Model路径(安装到非C盘)
  • 【计算机网络】第四章:网络层(上)
  • 【Linux-云原生-笔记】LVS(Linux virual server)相关
  • 云原生环境下的安全控制框架设计
  • MongoDB社区版安装(windows)
  • mongodb 入门级别操作
  • 如何清除 npm 缓存
  • Redis3:Redis数据结构与命令全解析
  • MongoDB 安装步骤详解
  • AI交互的初期魅力与后期维护挑战
  • RISC-V和ARM有何区别?
  • npm : 无法加载文件 C:\Program Files\nodejs\npm.ps1
  • Flutter状态管理篇之ChangeNotifier(一)
  • 深度学习之神经网络(二)