关于前后端自动携带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");
相关推荐
小羊没烦恼!2 天前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
脉动数据行情3 天前
Java OkHttp 对接国际期货批量行情 SpringBoot 定时落库实践
java·spring boot·okhttp
牧瀬クリスだ8 天前
Ajax入门:从原生XHR到axios实战
java·spring boot·ajax·okhttp
墨天梦12 天前
B15_HTTP解析与OkHttp拦截器
网络协议·http·okhttp
没差c1 个月前
RetrofitClient写接口、导包、配置、路径
java·spring boot·okhttp
事圆则缓1 个月前
OkHttp + Retrofit 协作原理
okhttp·retrofit
降临-max1 个月前
接口自动化(TestNG+OKHttp)
软件测试·okhttp·自动化·testng
吴声子夜歌1 个月前
Java扩展——OkHttp
java·开发语言·okhttp
额鹅恶饿呃1 个月前
Asynchronous JavaScript And XML(异步的JS和XML )
okhttp
泡海椒1 个月前
JQuick-Curl 性能分析:并发场景下的性能表现与调优,第三方接口调用不只要快写也要稳跑
java·开发语言·okhttp