如何获取后端数据?

时间:2020-08-10 19:39:12

标签: php reactjs

LogIn.js

export const logIn = (id, email, password) => {
return (dispatch) => {
    const config = {
        method: 'post',
        url: 'http://localhost/cup/u_select_info.php',
        body: JSON.stringify({
            id: id,
            email: email,
            password: password
        })
    };
    axios.request(config)
        .then((res) => {
            return res.json()
        })
        .then((responseJson) => {
            alert(responseJson);
        })
        .catch((error) => {
            console.log(error);
        })
}}

服务器

 <?php
include("./conn.php");
header("Access-Control-Allow-Origin:http://localhost:3000");
header("Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Headers, X-Requested-With");

$json = file_get_contents("php://input");
$obj = json_decode($json, true);

$id = $obj['id'];
$email = $obj['email'];
$password = $obj['password'];

if (isset($json) && !empty($json)) {

    $sql = "select * from u_info where id='$id' and email='$email' ";

    $insert_query = $conn->query($sql);

    if ($insert_query->num_rows !== 0) {
        echo json_encode('wrong');
    } else {
        echo json_encode('ok');
    }
} else {
    echo json_encode('try again');
}

当我单击登录按钮时,开发工具告诉我

enter image description here

也是网络响应

enter image description here

为什么后端消息“重试”不能显示我的首页?

1 个答案:

答案 0 :(得分:0)

if (isset($json) && !empty($json)) 

如果无法使用if语句,则这两个条件相互矛盾。

尝试以下if语句:

<?php
include("./conn.php");
header("Access-Control-Allow-Origin:http://localhost:3000");
header("Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Headers, X-Requested-With");

$json = file_get_contents("php://input");
$obj = json_decode($json, true);

$id = $obj['id'];
$email = $obj['email'];
$password = $obj['password'];

if (!empty($json)) {

    $sql = "select * from u_info where id='$id' and email='$email' ";

    $insert_query = $conn->query($sql);

    if ($insert_query->num_rows !== 0) {
        echo json_encode('wrong');
    } else {
        echo json_encode('ok');
    }
} else {
    echo json_encode('try again');
}

这意味着empty()本质上等同于 !isset($ var)|| $ var == false。 https://www.php.net/manual/en/function.empty.php#refsect1-function.empty-parameters

相关问题