关于前后端自动携带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");
相关推荐
Ttang234 天前
Java爬虫:Jsoup+OkHttp实战指南
java·爬虫·okhttp
李庆政3704 天前
OkHttp的基本使用 实现GET/POST请求 authenticator自动认证 Cookie管理 请求头设置
java·网络协议·http·okhttp·ssl
无名-CODING5 天前
Java 爬虫进阶:动态网页、多线程与 WebMagic 框架实战
java·爬虫·okhttp
小李云雾6 天前
零基础-从ESS6基础到前后端联通实战
前端·python·okhttp·中间件·eclipse·html·fastapi
亿牛云爬虫专家6 天前
爬虫踩坑实录:OkHttp 接入爬虫代理报 Too many tunnel connections attempted 深度解析
爬虫·okhttp·https·爬虫代理·connect·隧道代理·ip 切换
Dxy123931021612 天前
Ajax如何发送列表数据
前端·ajax·okhttp
967713 天前
AJAX和Axios理解和关系
前端·ajax·okhttp
必胜刻15 天前
AJAX 请求理解
前端·ajax·okhttp·前后端交互
android_cai_niao15 天前
OkHttp 使用教程:从入门到精通(Kotlin)
okhttp·kotlin