gpt4 book ai didi

javascript - jQuery REST Session 不起作用,但在 POSTMan 中有效

转载 作者:搜寻专家 更新时间:2023-10-31 20:35:19 25 4
gpt4 key购买 nike

我正在尝试构建一个基于 PHP 的 REST API,但我被这个问题困住了。我在 PHP 代码中有 session_start() 和一个简单的登录、注销脚本,它接受相同的 usernamepassword 进行身份验证:

<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json");
$message = array();
if ($_GET["action"] == "signin") {
if (count($_POST) && isset($_POST["username"]) && isset($_POST["password"]) && $_POST["username"] == $_POST["password"]) {
$message["user"] = $_POST["username"];
$message["success"] = true;
$_SESSION["user"] = $message["user"];
} else {
unset($message["user"]);
$message["success"] = false;
unset($_SESSION["user"]);
}
} elseif ($_GET["action"] == "signout") {
session_destroy();
$message["success"] = true;
} elseif ($_GET["action"] == "whoami") {
$message["success"] = true;
$message["user"] = isset($_SESSION["user"]) ? $_SESSION["user"] : "Guest";
}
die(json_encode($message));
?>

我正在使用 POSTMan(Chrome 扩展)登录并检查,一切正常。但是当我使用我的 jQuery 的 $.getJSON()$.post() 方法时,当我尝试 action=whoami 时,我只是获取 Guest。我的 jQuery 代码:

$.getJSON("http://localhost/api.php?action=whoami");
// Gives Guest. Okay! :)
$.post("http://localhost/api.php?action=signin", {
username: "admin", password: "admin"
});
// Gives me success with the user logged in.
$.getJSON("http://localhost/api.php?action=whoami");
// Gives Guest Again! :O

我已经使用 POSTMan 尝试过同样的事情,而且效果很好。但是使用 jQuery 这不起作用。所以,我尝试使用:

$.ajaxSetup({
cache: false
});

尽管如此,我也试过像这样附加一个随机字符串,但响应相同:

也不是这个。有人可以帮我继续吗?这对我来说是一个表演终结者。

$.getJSON("http://localhost/api.php?action=whoami");
// Gives Guest. Okay! :)
$.post("http://localhost/api.php?action=signin", {
username: "admin", password: "admin"
});
// Gives me success with the user logged in.
$.getJSON("http://localhost/api.php?action=whoami&kill=cache");
// Gives Guest Again! :O

最佳答案

session 通常存储在 Cookie 中。因此,当您发出跨域请求时,不会共享 Cookie。一个简单的修复方法是使用 proxy.php 但现在我得到了使用命名 session 的最佳解决方案。

使用以下代码获取您的sid:

<?php
if (isset($_GET["sid"]))
session_id($_GET["sid"]);
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json");
var_dump(session_id()); // Gives you the SID.

从下一次开始,使用 sid 作为 GET 参数,这将检查服务器 session 并恢复 session 。

关于javascript - jQuery REST Session 不起作用,但在 POSTMan 中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37101982/

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