关于前后端自动携带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");
相关推荐
没差c10 天前
RetrofitClient写接口、导包、配置、路径
java·spring boot·okhttp
事圆则缓20 天前
OkHttp + Retrofit 协作原理
okhttp·retrofit
降临-max22 天前
接口自动化(TestNG+OKHttp)
软件测试·okhttp·自动化·testng
吴声子夜歌23 天前
Java扩展——OkHttp
java·开发语言·okhttp
额鹅恶饿呃24 天前
Asynchronous JavaScript And XML(异步的JS和XML )
okhttp
泡海椒24 天前
JQuick-Curl 性能分析:并发场景下的性能表现与调优,第三方接口调用不只要快写也要稳跑
java·开发语言·okhttp
泡海椒24 天前
JQuick-Curl 二次开发:自定义解析器、扩展点开发指南,如何把框架能力真正变成团队资产
java·开发语言·okhttp·maven
摇滚侠25 天前
《SpringBoot 3:入门与应用实战》第 9 章 跨域问题 阅读笔记 27
spring boot·笔记·okhttp
刘广睿1 个月前
断点续传与分片下载是怎么实现的?Range 请求在视频下载中的工程实践
okhttp·ffmpeg·音视频·下载·python3.11
泡海椒1 个月前
JQuick-Curl vs RestTemplate / OkHttp / OpenFeign:框架选型对比,谁更适合第三方接口调用?
okhttp