gpt4 book ai didi

javascript - 两台服务器,同一个域名,取不到cookies

转载 作者:行者123 更新时间:2023-11-30 11:42:15 25 4
gpt4 key购买 nike

标题说明了一切,我无法弄清楚为什么我无法从同一域中的两个不同服务器获取或设置 cookie。 $path 设置为 /$domain 指定为 127.0.0.1$secure 设置 false$httponly 设置 false

这里是更详细的情况:

服务器 1 - 127.0.0.1

On Server 1 I have a PHP script that gets a cookie if it's set, and sets a new cookie. Then the old and new cookie values are returned as JSON.

服务器 2 - 127.0.0.1:8000

On Server 2 with the same domain name but a different port, I have an HTML file that requests the script from Server 1. I cannot get the cookie, or set a new one from Server 2.

文件如下:

服务器 1 上的 PHP 脚本

<?php

header ('Access-Control-Allow-Origin: *');

$old = !empty ($_COOKIE['test']) ? $_COOKIE['test'] : 'none';
$new = rand (0, 1000);

setcookie ('test', $new, time () * 2, '/', '127.0.0.1', false, false);

echo json_encode ('old: ' . $old . ' new: '. $new);

服务器 2 上的 HTML 文件

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<title></title>

<script type="text/javascript">
var test = new XMLHttpRequest ();

test.onreadystatechange = function ()
{
if (this.readyState !== 4 || this.status !== 200) {
return;
}

document.body.innerHTML = JSON.parse (this.responseText);
};

test.open ('POST', 'http://127.0.0.1/cookieget.php', true);
test.send ();
</script>
</head>

<body></body>
</html>

“这到底是怎么回事?!”

最佳答案

虽然这两个服务器具有相同的主机名,但它们具有不同的端口,因此它们是不同的来源。并且浏览器不会让您设置 cookie 跨源。

只有当两个源具有相同的方案、主机名和端口时,它们才被认为是相同的。

关于javascript - 两台服务器,同一个域名,取不到cookies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42191667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com