关于前后端自动携带cookie跨域问题

前端自动携带cookie配置

css 复制代码
	let v = document.getElementById("txt").value;
			let url = 'http://127.0.0.1/verify';
			
			//axios 携带cookie
			const options = {
			  method: 'POST',
			  url: url,
			  headers: {'content-type': 'application/json'},
			  withCredentials:true,
			  data: {code: '11'}
			};
			
			axios.request(options).then(function (response) {
			  console.log(response.data);
			}).catch(function (error) {
			  console.error(error);
			});

			  
			  
			  // fetch 携带cookie
			  const options = {method: 'POST',
			   headers: {
			   'Content-Type': 'application/json'
			   },
				credentials: 'include',
			    body: '{"code":"11"}'
			  };
			  
			  fetch(url, options)
			    .then(response => response.json())
			    .then(response => console.log(response))
			    .catch(err => console.error(err));
			  
			  
			  
			// ajax 携带cookie  
			$.ajax({
				url: url,
				type: 'POST',
				dataType: 'json',
				contentType: "application/json",
				data:JSON.stringify({'code':v}),
				xhrFields: {
								withCredentials: true
							},
				success: function(res){
					// 成功处理逻辑
					console.log(res)
				 },
				error: function(res){
					// 错误时处理逻辑
					}
						});
			 }

后端配置

css 复制代码
 response.setHeader("Access-Control-Allow-Origin", origin);
       response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
       response.setHeader("Access-Control-Max-Age", "3600");

       //允许后端携带的请求头
       response.setHeader("Access-Control-Allow-Headers", "X-Custom-Header, Upgrade-Insecure-Requests,Accept,Content-Type, x-requested-with,withCredentials,credentials");
       // 是否允许跨源请求携带凭据(如 Cookie、TLS 客户端证书或包含用户名和密码的认证头)
       response.setHeader("Access-Control-Allow-Credentials","true");
相关推荐
YF021115 小时前
深度解构Android OkDownload断点续传
android·数据库·okhttp
右耳朵猫AI3 天前
Python技术周刊 2026年第14周
开发语言·python·okhttp
牢七4 天前
cve研究
okhttp
yqcoder5 天前
原生 AJAX 揭秘:如何使用 XHR 发起请求
前端·ajax·okhttp
身如柳絮随风扬7 天前
你知道什么是 Ajax 吗?—— 从入门到原理,一篇彻底搞懂
前端·ajax·okhttp
小白学大数据12 天前
Python 自动化爬取网易云音乐歌手歌词实战教程
爬虫·python·okhttp·自动化
前端百草阁14 天前
【吃透 Promise】从基础到面试高频(手写 + 输出题 + 原理)
okhttp·面试·职场和发展
ppandss116 天前
JavaWeb从0到1-DAY4-AJAX
前端·ajax·okhttp
4311媒体网20 天前
织梦CMS点击率统计实现方法
okhttp
帅次21 天前
链路到端上:HTTPS 之后安全题还在考什么
android·okhttp·glide·zygote·retrofit