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

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.xdnf.cn/news/15582.html

相关文章:

  • 人工智能基础知识笔记十四:文本转换成向量
  • Android 实现:当后台数据限制开启时,仅限制互联网APN。
  • 什么是“数据闭环”
  • Docker-Beta?ollama的完美替代品
  • MySQL高可用集群架构:主从复制、MGR与读写分离实战
  • TDengine 的可视化数据库操作工具 taosExplorer(安装包自带)
  • VMware Workstation Pro 17下载安装
  • VR全景园区:开启智慧园区新时代
  • 基于C#+SQlite开发(WinForm)个人日程管理系统
  • 【leetcode】852. 山脉数组的封顶索引
  • 树莓派Qt 安装
  • CDSS系统升级“可视化解释-智能反馈-临床语言“三位一体设计架构设计分析
  • nginx代理websocket请求
  • 【华为】交换机vlan互访实验
  • 语雀编辑器内双击回车插入当前时间js脚本
  • 取消office word中的段落箭头标记
  • Java零基础快速入门
  • Vue3入门-组件及组件化
  • Kafka——无消息丢失配置怎么实现?
  • SpringMVC核心注解:@RequestMapping详解
  • java-字符串
  • modelscope ProxyError: HTTPSConnectionPool(host=‘www.modelscope.cn‘, port=443)
  • JxBrowser 7.43.5 版本发布啦!
  • HTML 常用语义标签与常见搭配详解
  • 图片画廊浏览(侧重 CSS 网格布局和模态框交互)
  • 代码随想录算法训练营第二十二天
  • 项目学习笔记 display从none切换成block
  • 基于SD-WAN的智慧高速解决方案:高效、低成本的智能交通实践
  • 数据结构 双向链表(2)--双向链表的实现
  • Kotlin集合聚合