CORS Ajax请求:Set-Cookie失败



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

响应标头

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伪代码

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

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

session_start();
print_r($_SESSION);

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

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

发现$。Ajax请求应该包含

withCredentials:真正的

crossDomain:真

在服务器端,脚本需要:

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

最新更新