0

I cobbled together the following Javascript from some tutorials. Everything works, my form submits and sends the data to a REST API where I have some Python to process it. I'd like to improve the script by somehow getting the text that the API returns in the http response, so that I can then display that response as a success message in my HTML page. I can see the response details in the array returned by fetch to the console.log but can't see the text that the API responds with.

        <script>
            // Event listener for form
            document.getElementById('note-form').addEventListener('submit', sendDataToLambda);

            // Function to send data to API
            function sendDataToLambda(e)
            {
                console.log('Submit clicked')
                e.preventDefault();

                // Gets the values of each field in our form.
                var formSubject = document.getElementById('subject').value;
                var formBody = document.getElementById('body').value;

                var endpoint = 'https://xxxx.execute-api.us-east-1.amazonaws.com/default/xxx';
                var body =
                {
                    subject: formSubject,
                    body: formBody
                }

                // Instantiate the request
                var lambdaRequest = new Request(endpoint,
                {
                    method: 'POST',
                    // 'no-cors' mode is for development on localhost only!
                    mode: 'no-cors',
                    body: JSON.stringify(body)
                });

                if (formSubject)
                {
                    console.log('Attempting to send..')
                    // Call the Fetch API to make our request
                    fetch(lambdaRequest)
                        .then(response => console.log(response))
                        .catch(err => console.log(err));
                    // Clear the form
                    document.getElementById("note-form").reset();
                    document.getElementById("sent").style.display = ''
                    setTimeout(function() {document.getElementById("sent").style.display = 'none'}, 3000)

                }
            }
        </script>
``
rcx935
  • 217
  • 5
  • 15
  • Do it in the `.then()` of the `fetch`. You can't get it out of that. – zero298 Jun 05 '20 at 20:20
  • The response has methods which return promises, which resolve to the text or JSON (depending on the method). – trincot Jun 05 '20 at 20:23
  • Check out [the documentation](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch), specifically the section entitled "Uploading JSON data" for a complete example – Kryten Jun 05 '20 at 20:24

0 Answers0