发送Ajax请求后如何检查用户是否登录成功?

一般来说,在向 PHP 后端发送 JS ajax 请求后,我是否需要添加 http_response_code(201); 在检查用户提交的数据在 PHP 代码中是正确的之后,我可以在 axios 中使用 then() 吗?如果提交的数据有问题我需要添加 http_response_code(401); 所以 catch() 部分将被触发,这个 http_response_code 是必须的吗?(我的意思是它是如何工作的?)因为我可能想检查它是否是内部服务器错误(500)或只是未经授权的用户错误(401)以向用户显示方便的错误消息。这就是专业项目中的做法吗?

例子 :

JS:

axios.post('http://localhost/PHPFiles/UserAuthentification.php',null,config)

                    .then((response) => {

                        if(response.status == 200)

                        this.GetData();

                    })

                    .catch((error) => {

                        if (error.response.status == 401) {

                              this.ShowUnauthorizedUserMessage();

                            }

                        if(error.response.status == 500){

                              this.ShowServerErrorMessage();

                            }

                    });

PHP:


<?php

$serverName = "localhost";

$userName = "root";

$userPassword = "";

$dataBase = "todosdbs";

try{

$con = new mysqli($serverName,$userName,$userPassword,$dataBase);

$data = json_decode(file_get_contents('php://input'),false);

$stmt = $con->prepare("SELECT userid,username,userpassword,useremail FROM users WHERE useremail = ?");

$stmt->bind_param("s",$data->currentUserEmailText);

$stmt->execute();

$result = $stmt->get_result();

}catch(exception $e){

    http_response_code(500);

    die("server error");

}

if($result->num_rows>0){

    try{

    $row = $result->fetch_array(MYSQLI_ASSOC);

    }catch(exception $e){

        http_response_code(500);

        die("server error!"); 

    }

    $pass = $row['userpassword'];

    if(password_verify($data->currentUserPasswordText,$pass)){

        http_response_code(200);

    }

    else{

        http_response_code(401);

        die("Unauthorized User!");

    }

}

else{

    http_response_code(401);

    die("Unauthorized User!");

}

?>

http_response_code(number) 也是如此;您如何从 PHP 后端检查客户端接下来要执行哪些代码?最后一个问题是 201 代码是否正确,用于通知客户端请求已在 PHP 后端成功实现(如我的示例或其 200 中所示)?


qq_花开花谢_0
浏览 152回答 2
2回答

慕容708150

您可以这样做,但是对于仅验证用户/通行证而言,执行基于服务器的错误代码可能有点严厉。我个人只是将响应保留在活动状态,就像您点击要查找的页面并且该页面知道要做什么一样,我将其保留为并只发回一个200json 数组,如下所示:die(json_encode([&nbsp; &nbsp; # $valid would be a boolean based on your login/pass validation success&nbsp; &nbsp; 'success' => $valid,&nbsp; &nbsp; # Depending on success, show appropriate msg&nbsp; &nbsp; 'alert' => ($valid)? 'Successful login' : 'Invalid Username or Password',&nbsp; &nbsp; # Send back data if necessary&nbsp; &nbsp; 'data' => false]));所以它可能看起来更像是:/functions.php<?phpfunction connect(){&nbsp; &nbsp; return new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);}function getUser($username, $con){&nbsp; &nbsp; $stmt = $con->prepare("SELECT * FROM users WHERE useremail = ?");&nbsp; &nbsp; $stmt->bind_param("s", $username);&nbsp; &nbsp; $stmt->execute();&nbsp; &nbsp; $result = $stmt->get_result();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if($result->num_rows == 0)&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; return $result->fetch_array(MYSQLI_ASSOC);}function userValid($user, $password){&nbsp; &nbsp; return password_verify($password, $user['userpassword']);}function ajaxResponse($success, $data = false, $msg = false){&nbsp; &nbsp; die(json_encode([&nbsp; &nbsp; &nbsp; &nbsp; 'success' => $success,&nbsp; &nbsp; &nbsp; &nbsp; 'data' => $data,&nbsp; &nbsp; &nbsp; &nbsp; 'msg' => $msg,&nbsp; &nbsp; ]));}/config.php<?phpdefine('ROOT_DIR', __DIR__);define('DB_HOST', "localhost");define('DB_NAME', "todosdbs");define('DB_USER', "root");define('DB_PASS', "");include(ROOT_DIR.'/functions.php');/PHPFiles/UserAuthentification.php<?phpinclude(__DIR__.'/../config.php');# Send json header since that is what is returningheader('Content-Type: application/json');try{&nbsp; &nbsp; # Fetch the database connection&nbsp; &nbsp; $con = connect();&nbsp; &nbsp; # Fetch the post&nbsp; &nbsp; $POST = json_decode(file_get_contents('php://input'),false);&nbsp; &nbsp; # Fetch the user, inject username and db&nbsp; &nbsp; $user = getUser($POST->currentUserEmailText, $con);&nbsp; &nbsp; # Stop if username invalid&nbsp; &nbsp; if(!$user) {&nbsp; &nbsp; &nbsp; &nbsp; ajaxResponse(false, false, "Invalid user");&nbsp; &nbsp; }&nbsp; &nbsp; # Check validation&nbsp; &nbsp; $response = (userValid($user, $POST->currentUserPasswordText))? [&nbsp; &nbsp; &nbsp; &nbsp; 'success' => true,&nbsp; &nbsp; &nbsp; &nbsp; 'data' => $user,&nbsp; &nbsp; &nbsp; &nbsp; 'msg' => 'User logged in successfully'&nbsp; &nbsp; ] : [&nbsp; &nbsp; &nbsp; &nbsp; 'success' => false,&nbsp; &nbsp; &nbsp; &nbsp; 'data' => false,&nbsp; &nbsp; &nbsp; &nbsp; 'msg' => 'Invalid username or password'&nbsp; &nbsp; ];&nbsp; &nbsp; # Report back&nbsp; &nbsp; ajaxResponse(...$response);}catch(\Exception $e) {&nbsp; &nbsp; # Report back error if it occurs&nbsp; &nbsp; ajaxResponse(false, false, $e->getMessage());}

慕田峪4524236

使用 HTTP 状态代码(2xx 表示成功,4xx 表示错误,...)非常适合提供有关请求进行情况的总体了解。通常,您还希望在响应正文中添加其他详细信息,并进行编码,以便客户端可以轻松读取它们(例如 JSON),以便向客户端提供有关错误的更清晰提示(并区分所有可能的结果!)。例如,成功响应可能具有 200 状态代码并具有以下正文: {"type":"sucess", "message": "User logged in successfully"}虽然无效的登录尝试通常会导致 403 状态代码,并且响应可能如下所示: {"type":"error", "message": "Invalid username or password"}但是,假设您想要说明具有给定电子邮件地址的帐户是否存在(例如 Trello),那么您将为这两个响应使用 403 状态代码,但具有不同的正文:{"type":"error", "message": "There is no account corresponding to the given email"} {"type":"error", "message": "Invalid password"}使用 401 状态代码表示需要进行身份验证才能访问资源,如果用户浏览到此页面,通常浏览器会显示这样的登录提示(但这不适用于 ajax 请求)。失败的登录尝试应该得到 403 状态代码。您可以查看维基百科以获取有关状态代码的详细信息以及有关浏览器如何解释它们的一些提示。旁注:在成功登录的情况下,您似乎不会返回任何令牌,也不会设置 cookie,您肯定希望这样做以确保用户在后续请求中登录。如果您正在寻找身份验证示例,可以查看 oAuth2 服务器或Firebase 身份验证 API。
打开App,查看更多内容
随时随地看视频慕课网APP