Error making a POST request for my API in PHP

Viewed 19

The function of this API is to insert into the database of a form submitted from the frontend. The code for my backend and my frontend are as follows:

function App() {
  const [newPost, setNewPost] = useState({
    title: null,
    body: null
  });

  const registerNote = async e => {
    e.preventDefault();
    await fetch("http://localhost/test/api/insert.php", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(newPost)
    })
      .then(response => response.json())
      .then(response => console.log(response));
  }

  return (
    <div className="App">
      <form onSubmit={registerNote} method='POST'>
        <input name='title' type="text" onChange={e => setNewPost({ ...newPost, title: e.target.value })} placeholder='Enter the title of the note' />
        <input name='body' type="text" onChange={e => setNewPost({ ...newPost, body: e.target.value })} placeholder='Insert the body of the note' />
        <button>Register Note</button>
      </form>
    </div>
  );
}

export default App;

<?php

$db_host = 'fake';
$db_name = 'fake';
$db_user = 'fake';
$db_pass = 'fake';

$pdo = new PDO("mysql:dbname=$db_name;host=$db_host", $db_user, $db_pass);

$array = [
    'error' => '',
    'result' => []
];

$request_method = strtoupper($_SERVER['REQUEST_METHOD']);

if ($request_method === 'POST') {
    $title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_SPECIAL_CHARS);
    $body = filter_input(INPUT_POST, 'body', FILTER_SANITIZE_SPECIAL_CHARS);

    if ($title && $body) {
        $sql = $pdo->prepare("INSERT INTO notes (title, body) VALUES (:title, :body)");
        $sql->bindValue(':title', $title);
        $sql->bindValue(':body', $body);
        $sql->execute();

        $id = $pdo->lastInsertId();

        $array['result'] = [
            'id' => $id,
            'title' => $title,
            'body' => $body
        ];
    } 
    else {
        $array['error'] = 'Problem sending the data.';
    }
} 
else {
    $array['error'] = 'Invalid request method.';
}

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Content-Type: application/json");
echo json_encode($array);
exit;

The problem is that my return on the front end is always the same:

{error: 'Problem sending the data.', result: Array(0)}

That is, it always acts as if it did not receive the data correctly. I've tried a lot of things, so I'm resorting to answers from here.

0 Answers
Related