简体   繁体   English

JS Fetch 无法使用 PHP API 后端发布 JSON

[英]JS Fetch failing to POST JSON with a PHP API backend

I have been trying to connect to my server to send and receive data, but for some reason I can only GET data back, but not POST data.我一直在尝试连接到我的服务器以发送和接收数据,但由于某种原因我只能返回 GET 数据,而不能返回 POST 数据。 I am using the JS Fetch API, but have also tried using the XMLHttpRequest with similar results.我正在使用 JS Fetch API,但也尝试过使用 XMLHttpRequest 得到类似的结果。 I don't receive any error logs except for the catch error that I create, so any help would be fantastic!除了我创建的捕获错误之外,我没有收到任何错误日志,所以任何帮助都会很棒!

Frontend JS POST Users - Does not Work前端 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;
}

Backend PHP Create User (AKA create.php. This is what I am calling from the JS side.)后端 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')
    );
  }
?>

Backend PHP User class后端 PHP 用户 class

<?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;
            }
        }
?>

UPDATE: I have tried to use async and await thinking I was using fetch wrong, but that still didn't work.更新:我曾尝试使用 async 并 await 认为我使用的 fetch 错误,但仍然没有用。 I am beginning to think the problem is more on the apache server side, though I am not sure why because GET works.我开始认为问题更多在 apache 服务器端,但我不确定为什么因为 GET 有效。

Found a simple solution and forgot to actually put it on here, but the answer is to add an event object to the frontend JS then use the prevent default function to stop the default handling of forms and prevents the page from refreshing for FireFox, Safari and the like.找到了一个简单的解决方案,忘记实际放在这里了,但答案是在前端JS中添加一个事件object然后使用阻止默认function停止默认处理forms并防止页面刷新FireFox,8837867556558 8和类似。 So it looks like this:所以它看起来像这样:

function setUser(event) {
    event.preventDefault();
    ...
    console.log("Everything else started working...");
}

Note: This worked on Chrome with AND without this event object.注意:这在 Chrome 上工作并且没有这个事件 object。

Try to add Content-Type: application/json for header尝试为header添加Content-Type: application/json

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

Result will be in JSON as you need:根据您的需要,结果将在 JSON 中:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM