首页 > 解决方案 > 从使用 axios 调用响应启动 php 会话不会使会话保持活动状态,但是使用邮递员执行它就可以了

问题描述

我知道存在类似这样的其他问题,但我未能成功实施任何这些问题,这意味着没有一个有效,无论是由于我自己的错误还是他们固有的无能解决这个问题。

环境:

我正在为 php 项目提供服务,php -S 127.0.0.1:8080并在默认端口(3000)上启动了一个反应前端npm start。我正在使用 axios 向服务器发出请求。

相关代码:

我有 2 个非常重要的文件:

useEffect(() => {
    axios({
      method: "get",
      url: "http://localhost:8080/phpfolder/test1page.php?username=username",
      dataType: "JSON",
    })
      .then((response) => {
        console.log("response here", response.data);
        setUserName(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  useEffect(() => {
    if (userName !== "") {
      axios({
        method: "get",
        url: "http://localhost:8080/phpfolder/test1page.php",
        dataType: "JSON",
      })
        .then((response) => {
          console.log("response here", response.data);
        })
        .catch((error) => {
          console.log(error);
        });
    }
  }, [userName]);
    <?php 
     session_start();
     header("Access-Control-Allow-Origin: *");
     header('Access-Control-Allow-Headers: Content-Type');
    
     if (isset($_GET['username'])) {
        $_SESSION['username'] = $_GET['username'];
        // echo  $_SESSION['username'];
     }
    
     if(!isset($_SESSION['username'])){
        echo 'you are not logged in';
    }else{
        echo 'you are logged in';
        header('Content-type: application/json');
        echo json_encode($_SESSION);
    }
    
     ?>

问题 :

我的问题是,虽然第一个请求验证没有问题:

you are logged in{"username":"username"}

第二个请求没有找到实时会话:

you are not logged in

尝试过的解决方案/调试:

我尝试了很多解决方案,包括设置withCredentials: falsetrue. 将其设置为 true 会导致 Cors 错误。我已经从 php 文件中添加和删除了各种头文件(一些用于 Cors,一些用于解决这个问题):

header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Origin: http://localhost:3000");
header('Access-Control-Allow-Origin: *'); 
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
header("Content-type:application/json");
header("connection:keep-alive");

我已经尝试过邮递员并发送一个请求来启动会话,然后另一个来检查它是否还活着就可以了:

您已登录{

在此处输入图像描述

标签: javascriptphpreactjssessionaxios

解决方案


我找到了解决方案。详细的解释可以在这篇关于 Cors 的文章中找到。相关部分位于 Credentials and Cors 部分。简短的回答是您必须将 withcredentials 标志设置为 true,这将导致 Cors 错误问题,然后您可以通过在后端添加适当的标头来修复该问题:

header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");

这就是我的页面现在一切正常的样子:

  • 登录页面.js:

    useEffect(() => {
        axios({
          method: "get",
          url: "http://localhost:8080/phpfolder/test1page.php?username=username",
          dataType: "JSON",
          withcredentials: true
        })
          .then((response) => {
            console.log("response here", response.data);
            setUserName(response.data);
          })
          .catch((error) => {
            console.log(error);
          });
      }, []);
    
      useEffect(() => {
        if (userName !== "") {
          axios({
            method: "get",
            url: "http://localhost:8080/phpfolder/test1page.php",
            dataType: "JSON",
            withcredentials: true
          })
            .then((response) => {
              console.log("response here", response.data);
            })
            .catch((error) => {
              console.log(error);
            });
        }
      }, [userName]);

  • test1page.php:

     <?php 
      session_start();
      header("Access-Control-Allow-Origin: http://localhost:3000"); // cannot be a wildcard, you have to specify the name of the domain making the request here.
      header('Access-Control-Allow-Headers: Content-Type');
      header("Access-Control-Allow-Credentials: true"); // add this header
    
      if (isset($_GET['username'])) {
         $_SESSION['username'] = $_GET['username'];
         // echo  $_SESSION['username'];
      }
    
      if(!isset($_SESSION['username'])){
         echo 'you are not logged in';
     } else {
         echo 'you are logged in';
         header('Content-type: application/json');
         echo json_encode($_SESSION);
     }
    
      ?>
    

推荐阅读