我正在通过网站 https://a.com 进行身份验证。身份验证后,我将访问 http://b.com。 a.com 为会话设置一个 cookie,当我从 b.com 向 a.com 发出 get 请求时,我需要发送该 cookie。
您能否告诉我,如何获取 cookie 并通过我的请求传递它。
我尝试使用“withCredentials”发送请求:true, 还尝试将 axios-cookiejar-support 与tough-cookie 一起使用。但好像没用。
axios
.get(a.com/path-requiring-cookie, {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
'access-control-allow-credentials': true,
},
})
.then(res => {
console.log(res.data);
});
这是我必须发送请求的代码。
但这似乎并没有随请求发送cookie。 有人可以澄清一下吗?
为什么不使用 JavaScript 函数来帮助根据名称获取 Cookie,如下所示
function GetCookie(cName) {
const name = `${cName}=`;
const decodedCookie = decodeURIComponent(document.cookie);
const ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return '';
};
console.log(GetCookie("SID"))
看看这个问题。
您要解决的问题是从不同的域读取cookie或向不同的域发送cookie。
一个解决方案,如前面链接的问题中所述,是在
http://b.com
上设置一些标题
Access-Control-Allow-Origin: http://b.com
Access-Control-Allow-Credentials: true
您在具有域的服务器上执行此操作
http://b.com
按照这些思路应该可以解决您的问题。