JS获取无法使用PHP API后端POST JSON

mwyxok5s  于 2023-01-14  发布在  PHP
关注(0)|答案(1)|浏览(126)

我一直在尝试连接到我的服务器发送和接收数据,但由于某种原因,我只能获取数据,但不能POST数据。我正在使用JS获取API,但也尝试使用XMLHttpRequest与类似的结果。我没有收到任何错误日志,除了我创建的捕获错误,所以任何帮助将是梦幻般的!
前端JS POST用户-不工作

function setUsers() {
    const data = new FormData(apiform);
    const value = Object.fromEntries(data.entries());
    console.log(value);

    fetch("../backend/api/user/create.php", {
        method: "POST",
        body: JSON.stringify(value),
        mode: "cors",
        credentials: "same-origin",
        headers: {
           "Content-Type": "application/json"
        }
    })
    .then((response) => {
        if (response.ok) {
            response.json();
        } else {
            throw new Error("Bad Server Response! Response: " + response.status);
        }
    })
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error("ERROR: Failed to set users...");
    });

    return false;
}

后端PHP创建用户(AKA create.php。这是我从JS端调用的。)

<?php
  header('Access-Control-Allow-Origin: *');
  header('Content-Type: application/json');
  header('Access-Control-Allow-Methods: POST');
  header("Access-Control-Allow-Credentials: true");
  header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,
                                        Access-Control-Allow-Credentials,
                                        Content-Type,
                                        Access-Control-Allow-Methods,
                                        Authorization,
                                        X-Requested-With');

  include_once '../../config/Database.php';
  include_once '../../models/User.php';

  $database = new Database();
  $db = $database->connect();

  $user = new User($db);

  $data = json_decode(file_get_contents("php://input"));

  $user->username = $data->username;
  $user->password = $data->password;
  $user->email = $data->email;

  if($user->createUser()) {
    echo json_encode(
      array('message' => 'User Created')
    );
  } else {
    echo json_encode(
      array('message' => 'User Not Created')
    );
  }
?>

后端PHP用户类

<?php
    class User {
        private $conn;
        private $table = 'users';
        public $id;
        public $username;
        public $password;
        public $email;

        public function __construct($db) {
            $this->conn = $db;
        }

        public function getAllUsers() {
            $query = 'SELECT * FROM ' . $this->table . ' ORDER BY username ASC;';
            $stmt = $this->conn->prepare($query);
            $stmt->execute();

            return $stmt;
        }

        public function createUser() {
            $query = 'INSERT INTO ' . $this->table . ' SET username = :username, 
                                                           password = :password, 
                                                           email = :email';
            $stmt = $this->conn->prepare($query);

            $this->username = htmlspecialchars(strip_tags($this->username));
            $this->password = htmlspecialchars(strip_tags($this->password));
            $this->email = htmlspecialchars(strip_tags($this->email));

            $stmt->bindParam(':username', $this->username);
            $stmt->bindParam(':password', $this->password);
            $stmt->bindParam(':email', $this->email);

            if ($stmt->execute()) {
                return true;
            } else {
                printf("ERROR: %s.\n", $stmt->error);
                return false;
            }
        }
?>

更新:我试过使用async,但我认为我用错了fetch,但还是不起作用。我开始认为问题更多的是在apache服务器端,虽然我不知道为什么,因为GET起作用了。

4uqofj5v

4uqofj5v1#

尝试为header添加Content-Type: application/json

<?php
$data = array("a" => "Apple", "b" => "Ball", "c" => "Cat");
header("Content-Type: application/json");
echo json_encode($data);

结果将根据需要以JSON格式显示:

相关问题