【问题标题】:CORS Ajax Request: Set-Cookie failingCORS Ajax 请求:Set-Cookie 失败
【发布时间】:2021-11-19 23:20:55
【问题描述】:

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);

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

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

【问题讨论】:

    标签: php ajax cookies cross-domain setcookie


    【解决方案1】:

    发现$.ajax请求应该包含

    withCredentials: 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
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2017-05-20
      • 2019-07-17
      • 2017-04-02
      相关资源
      最近更新 更多