Search code examples
javascriptphppostget

How to convert GET request To POST request when using fetch()


I am currently trying to convert my old, insecure, short GET requests to a more secure POST request. I am not sure how to do it.

function fetchData() {
        return fetch(`dataProcessing?action=submit&data=${encryptedFormValue}`)
            .then((response) => response.json())
            .catch(error => {
                console.log(error, 'warn');
            });
    }

I also have a backend for this that receives at dataProcessing.php

} else if ($_GET["action"] == "submit") {
    echo '{"response": "' . processData($_GET["data"]) . '"}';

Does anyone know how to convert this basic function into a POST request from a GET request?

I have tried using ChatGPT, searching on various webpages such as GET vs POST Request: The Difference, and could not find anything useful. What I am currently programming has to be secure since its a message encrypting website and GET requests are just not secure enough. I even tried looking at other stack overflow questions and all of them were so confusing.


Solution

  • Just move the parameters that should be hidden from the URL to the body.

    function fetchData() {
      return fetch(`dataProcessing?action=submit`, {
          method: 'POST',
          body: `data=${encodeURIComponent(encryptedFormValue)}`
        })
        .then((response) => response.json())
        .catch(error => {
          console.log(error, 'warn');
        });
    }
    

    And use $_POST in the PHP code instead of $_GET (or use $_REQUEST so it works either way).