一般来说,在您向 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?
慕容708150
慕无忌1623718
相关分类