亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

發送 Ajax 請求后如何檢查用戶是否成功登錄?

發送 Ajax 請求后如何檢查用戶是否成功登錄?

慕桂英4014372 2022-10-13 15:57:17
一般來說,在您向 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?
查看完整描述

2 回答

?
慕容708150

TA貢獻1831條經驗 獲得超4個贊

您可以這樣做,但是對于僅驗證用戶/通行證而言,執行基于服務器的錯誤代碼可能有點笨拙。我個人只是將響應保持在活動狀態,就像您點擊您正在尋找的頁面并且頁面知道該做什么一樣,我將其保留為200并發送回一個 json 數組,如下所示:


die(json_encode([

    # $valid would be a boolean based on your login/pass validation success

    'success' => $valid,

    # Depending on success, show appropriate msg

    'alert' => ($valid)? 'Successful login' : 'Invalid Username or Password',

    # Send back data if necessary

    'data' => false

]));

所以它可能看起來更像:


/functions.php


<?php

function connect()

{

    return new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

}


function getUser($username, $con)

{

    $stmt = $con->prepare("SELECT * FROM users WHERE useremail = ?");

    $stmt->bind_param("s", $username);

    $stmt->execute();

    $result = $stmt->get_result();

    

    if($result->num_rows == 0)

        return false;


    return $result->fetch_array(MYSQLI_ASSOC);

}


function userValid($user, $password)

{

    return password_verify($password, $user['userpassword']);

}


function ajaxResponse($success, $data = false, $msg = false)

{

    die(json_encode([

        'success' => $success,

        'data' => $data,

        'msg' => $msg,

    ]));

}

/config.php


<?php

define('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


<?php

include(__DIR__.'/../config.php');

# Send json header since that is what is returning

header('Content-Type: application/json');


try{

    # Fetch the database connection

    $con = connect();

    # Fetch the post

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

    # Fetch the user, inject username and db

    $user = getUser($POST->currentUserEmailText, $con);

    # Stop if username invalid

    if(!$user) {

        ajaxResponse(false, false, "Invalid user");

    }

    # Check validation

    $response = (userValid($user, $POST->currentUserPasswordText))? [

        'success' => true,

        'data' => $user,

        'msg' => 'User logged in successfully'

    ] : [

        'success' => false,

        'data' => false,

        'msg' => 'Invalid username or password'

    ];

    # Report back

    ajaxResponse(...$response);

}

catch(\Exception $e) {

    # Report back error if it occurs

    ajaxResponse(false, false, $e->getMessage());

}


查看完整回答
反對 回復 2022-10-13
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

使用 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 狀態碼。您可以查看Wikipedia以獲取有關狀態代碼的詳細信息以及有關瀏覽器如何解釋它們的一些提示。

旁注:在成功登錄的情況下,您似乎沒有返回任何令牌或設置 cookie,您當然希望這樣做以確保用戶在后續請求中登錄。

如果您正在尋找身份驗證示例,您可以查看 oAuth2 服務器或Firebase 身份驗證 API。



查看完整回答
反對 回復 2022-10-13
  • 2 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號