Encountering a black screen when trying to retrieve user data from the backend
P粉921130067
P粉921130067 2024-03-29 11:08:15
0
1
365

On the frontend I'm using ReactJs and I've been trying to get the logged in user's data from the backend (PHP) via axios.get, set a condition for the user and if met they will be returned to the login page and the backend is returning nothing, The reason why the login is returned is because the file that the front end is responsible for processing data is empty, so nothing is returned.

I've set up the session, replaced $_SESSION[] with $_POST[], and placed these snippets at the top of the page:

error_reporting(E_ALL);
ini_set('display_errors','1');

But it has no effect and the error is not shown. I also tested in Postman and it returned empty, but when I tested in x-www-form-urlencoded with everything set and the keys and values ​​written in any possible way, it returned a 400 error, All fields are required.

Below I will post the code snippets for login and registration (where the user's input is processed to be sent to the database).

Log in

$db = _db();

    try {

        $q=$db->prepare("SELECT * FROM users WHERE email = :email");
        $q->bindValue(":email", $_POST["email"]);
        $q->execute();
        $row = $q->fetch();

        if(!empty($row)){

            if (password_verify($_POST["password"], $row["password"])) {

                $user = array(
                    "user_id" => $row["user_id"],
                    "first_name" => $row["first_name"],
                    "last_name" => $row["last_name"],
                    "email" => $row["email"],
                    "company" => $row["company"],
                    "phone_number" => $row["phone_number"],
                    "verified" => $row["verified"],
                    "token" => $row["token"],
                );


                header("Content-type: application/x-www-form-urlencoded");
                http_response_code(200);
                echo json_encode($user);
                exit();

            } else {
                header("Content-type: application/x-www-form-urlencoded");
                http_response_code(400);
                echo json_encode("Wrong email or password");
                exit();
            }
            
            } else {
                header("Content-type: application/x-www-form-urlencoded");
                http_response_code(400);
                echo json_encode("User does not exist");
                exit();
        
            }

Registration - Also set $_SESSION here because after confirming the account I plan to redirect the user directly to the dashboard

$q=$db->prepare("INSERT INTO users(user_id, first_name, last_name, company, email,     phone_number, password, forgot_password, token, verified) VALUES(:user_id, :first_name, :last_name, :company, :email, :phone_number, :password, :forgot_password, :token, :verified)");
            $q->bindValue(":user_id", null);
            $q->bindValue(":first_name", $firstName);
            $q->bindValue(":last_name", $lastName);
            $q->bindValue(":company", $company);
            $q->bindValue(":email", $email);
            $q->bindValue(":phone_number", $phoneNumber);
            $q->bindValue(":password", $passwordHash);
            $q->bindValue(":forgot_password", $forgotPass);
            $q->bindValue(":token", $token);
            $q->bindValue(":verified", false);
            $q->execute();

            $user_id = $db->lastInsertId();

            $to_email = $email;
            $subject = "Email subject";
            $message = "Click on the following link to verify your account:
                <a href='http://localhost/api/confirm_account.php?token=$token'>Confirm your account</a>";

            require_once(__DIR__."/emailVerification/send_email.php");

            $user = array(
                "user_id" => $_SESSION["user_id"] = $row["user_id"],
                "first_name" => $_SESSION["first_name"] = $row["first_name"],
                "last_name" => $_SESSION["last_name"] = $row["last_name"],
                "email" => $_SESSION["email"] = $row["email"],
                "company" => $_SESSION["company"] = $row["company"],
                "phone_number" => $_SESSION["phone_number"] = $row["phone_number"],
                "verified" => $_SESSION["verified"] = $row["verified"],
                "token" => $_SESSION["token"] = $row["token"],
            );
    

            header("Content-type: application/json");
            http_response_code(200);
            echo json_encode($user);
            exit();
        }
    }

This is how I handle POST/GET requests on the frontend

const handleLogInSubmit = (event) => {
    event.preventDefault();

    axios
      .post("http://localhost/api/login.php", {
        email: userInput.email,
        password: userInput.password,
      })
      .then((response) => {
        if (response.data) {
          navigate("/dashboard");
        } else {
          setErrorMessage("Login failed, try again");
        }
      })


 useEffect(() => {

    axios.get("http://localhost/api/login.php")
    .then((response) => {
      if(response.data){
        setUser(response.data);
        console.log(response.data)
      } else {
        console.log(response)
        navigate("/login");
      }
    });
}, [navigate]);

Output of login.php file

If you need to see the rest of the frontend and backend code, please let me know.

edit:

Now I can see what's wrong with the code, but even after receiving the message Login successful I still keep getting redirected to the login page and just see that axios.get doesn't retrieve any Content, only axios.post works:

P粉921130067
P粉921130067

reply all(1)
P粉364642019

The problem is that you are sending JSON data from the frontend but trying to extract it using $_POST According to the documentation works for x-www-form -urlencoded or multipart/form-data form data.

Instead of sending JSON data, you can send the data the backend expects, which is a string of query parameters:

.post("http://localhost/api/login.php", new URLSearchParams({
  email: userInput.email,
  password: userInput.password,
}))
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template