0

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.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • In english please – Jaromanda X Sep 21 '22 at 13:29
  • `it always enters the php else as if it had not received the title the body correctly`...exactly right. PHP does not parse JSON data automatically or put it into $_POST. See the duplicate, above. – ADyson Sep 21 '22 at 13:33
  • N.B. `FILTER_SANITIZE_SPECIAL_CHARS` is completely unnecessary for input data. You don't need to HTML-encode something when it's going into a database, it's not vulnerabl to XSS there. You only need to do that when you're _outputting_ the data, and then only when outputting it into a _HTML document_ (e.g. a web page). It's not a threat anywhere else. And you should use `htmlspecialchars()` for that purpose. By filtering it up-front you're potentially corrupting data which might be otherwise perfectly valid and useful. I'm not really sure why PHP even supports this filter, to be honest. – ADyson Sep 21 '22 at 13:36
  • what is `INPUT_POST`, did you mean using `$_POST['title']` and `$_POST['body']` ? – Sanidhya Oct 28 '22 at 06:04
  • @Sanidhya No. I suggest you read the [documentation for filter_input](https://www.php.net/manual/en/function.filter-input.php) so you understand what it does and what the constants are. I'd also recommend you read the duplicate question (in the blue box above) and the earlier comments here, then you'd realise that, even if it was correct, your comment is still irrelevant because the actual issue here is that JSON body data in the request isn't passed into the $_POST array by PHP, it has to be read using a different technique. – ADyson Oct 28 '22 at 07:22

0 Answers0