CORS Ajax 请求:Set-Cookie 失败

CORS Ajax Request: Set-Cookie failing

CORS方案为:

AJAX 电话来自:https://remotewebsite.com/

GET 请求到 http://localhost/?param=ThisIsImportant

我正在使用 localhost,因为它仍在开发中。

Request URL: http://localhost/?param=ThisIsImportant
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:80
Referrer Policy: strict-origin-when-cross-origin

回应Headers

Access-Control-Allow-Origin: *
Cache-Control: no-store, no-cache, must-revalidate
Connection: Keep-Alive
Content-Length: 226
Content-Type: text/html; charset=UTF-8
Date: Mon, 27 Sep 2021 20:18:08 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=100
Pragma: no-cache
Server: Apache/2.4.48 (Win64) OpenSSL/1.1.1k PHP/8.0.8
Set-Cookie: PHPSESSID=00fg461kl112lctp7ooqr5mder; path=/
X-Powered-By: PHP/8.0.8

PHP Pseudo-code

session_start();
$_SESSION['hash'] = $_GET['param'];

如果我输入 http://localhost 并访问脚本:

session_start();
print_r($_SESSION);

Session 为空。如果我在开发人员工具中检查 cookie,PHPSESSID 与 AJAX 响应中的不同。

我需要在 AJAX 响应期间设置 PHPSESSID 并保存,并且能够检索 PHP 上设置的 SESSION['hash']在 AJAX 请求期间。包括在本地主机上的另一个脚本中。这可能吗?

发现$.ajax请求应该包含

withCredentials: true

crossDomain: true

在服务器端,脚本需要:

header('Access-Control-Allow-Credentials: true');
session_set_cookie_params(["SameSite" => "none"]); //none, lax, strict
session_set_cookie_params(["Secure" => "true"]); //false, true
session_set_cookie_params(["HttpOnly" => "true"]); //false, true

就是这样。