当前位置: 首页 > 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.dtcms.com/a/284512.html

相关文章:

  • 当下主流摄像头及其核心参数详解
  • 不同场景下git指令的搭配
  • pycharm回车、删除、方向键和快捷键等不能使用原因
  • TRAE Agent 在 SWE-bench Verified 上得分 75.2%,并已开源
  • opencv、torch、torchvision、tensorflow的区别
  • Linux717 SWAP扩容;逻辑卷条带化
  • 前端-HTML
  • 杰理AC70NN项目用脚本自定义添加.mk文件,直接链接进主Makefile脚本编译
  • 开通腾讯位置复位
  • 深入理解Collections.addAll方法
  • 【华为】交换机vlan互访实验
  • 【人工智能99问】梯度消失、梯度爆炸的定义、后果及规避手段?(7/99)
  • JAVA面试宝典 -《Kafka 高吞吐量架构实战:原理解析与性能优化全攻略》
  • UE5多人MOBA+GAS 25、创建数据表初始化属性,使用MMC计算伤害
  • 模块化社交新范式:Moments用极简设计重构数字表达
  • 麒麟信安参编的三项软件供应链安全团体标准发布
  • 运维工程师面试题174道
  • 单片机最小系统硬件调试踩的一些坑
  • lesson16:Python函数的认识
  • Linux手动安装Nginx(基于Centos 7)
  • ESLint 完整功能介绍和完整使用示例演示
  • 01项目管理概论
  • Shell变量
  • 操作系统系统面试常问(进程、线程、协程相关知识)
  • Java使用FastExcel实现Excel文件导入
  • 基于springboot+vue+mysql框架开发的景区民宿预约系统的设计与实现(源码+论文)
  • 政务类产品的用户场景如何描述
  • STM32 DMA通信详解
  • Qt CMake 学习文档
  • 优化 CSS 性能