Home > Mobile >  How do I see why Axios POST request is not sending payload data to Heroku Backend?
How do I see why Axios POST request is not sending payload data to Heroku Backend?

Time:10-02

Goal: Frontend react app can send data to Heroku backend as a POST request.

Framework: React using Axios

I have been trying to set up breakpoints on the Axios post request function however it doesn't seem to be working. I have set a promise statement with .then however no response gets sent back to the console.

Below is React component and Axios POST being run when the submit takes place.

Any help on this matter would be greatly appreciated .

I have tested a POST request by POSTMAN and the data does have a status 200 and does get sent.

Also, I have updated with both a promise and try-catch. The Promise is commented out because I could not get it to work with the current syntax. If you feel that is best used, please look at the code and see why the syntax issues are.

import React from 'react';
 import {useState} from 'react';
 import Axios from 'axios'
 //import { response } from 'express';


 const QuoteForm = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [question, setQuestion] = useState("");



  /* This is the promise version however it has sytax issues : 
  the funtion containing the promise doesn't properly close so return expects } instead has ) 



   const custData =  { name:name , 
    email:email , 
    question:question} ;



   const submitQuestion =  new Promise ((resolve, reject)=>
  
    resolve(Axios.post('https://hookahsite-backend.herokuapp.com  || https://localhost:8000 ' , custData)
    .then(()=> {console.log("success, data sent")})
    .catch(()=>{console.log("error when sending")})
    )
    
  
   
 */ 

    //this uses try catch however the backend is not getting hit with any data
    //tested this same request in Postman and it works 
    function submitQuestion() { 
      try {
       Axios.post('https://hookahsite-backend.herokuapp.com ' ,
      {
        name:name , 
        email:email , 
        question:question
        
      },
      )
      }
      catch (err) {console.error(err);}
        }
         






     return(
         <React.Fragment>



     <form id="quoteForm" 
     
     >
       <h1 id="quoteTitle">Quote Help Form</h1>
       <p id="quotePar">Please provide your Name, Contact Email, and what products you would like more information about in this form :</p>

   <label id="formName" className="Form">
     Name:
     <input type="text" name="name" 

     onChange={(event) => { setName(event.target.value);}}

     />
   </label>

   <label id="formEmail" className="Form">
     Email:
     <input type="text" name="email" 
     onChange={(event) => { setEmail(event.target.value);
     }}/>
   </label>
   <br/>
   <label id="formQuestion" className="Form" >
     What products would you like to know more about:
     <input type="text" name="help" 
     onChange={(event) => { setQuestion(event.target.value);
     }}/>
   </label>

   <br/>
   <br/>

   <button id="quoteSubmit" type="submit" 

   onClick = 
   {
     submitQuestion
     
   }

   /*
   old way
      {()=>
    
    submitQuestion()
    
  }
  */

   >Submit </button>

   </form></React.Fragment>

     )
 };

 export default QuoteForm; 

Serverside Code:

Note the Try Catch on the front end receives no error to throw. The backend code also should be sending a console log and is not. Now if I send this by postman there is a console log and it has status 200

app.post('/' , (req,res) => {
    const {email, name, question} = req.body;
    res.header("Access-Control-Allow-Origin", "*");
    console.log(`Your Email is ${email} and your name is ${name} and your ${question}`);



//MYSQL updating table

pool.query("INSERT INTO customer_questions (name, email, question) VALUES (?,?,?)",
    [name, email, question], (err,res)=> {
        if (err) {
            console.log(err)
        }else {
            res.send('data sent')
        }
        
    }
    );


});

CodePudding user response:

Here is the two options you have:

Promises or async/await.

They have different advantages and disadvantages I suggest you look into both of them (read the docs or see videos about them) they basically do the same, but in a different way.

This code is untested, so apologies if there is any syntax error.

// Promise option 
const funcWithPromise = () => {  
 Axios.post('https://hookahsite-backend.herokuapp.com  || https://localhost:8000 ' , custData)
 .then( (axiosResponse)=> { 
                  // here you can use the data 
                  const submitQuestions = axiosResponse.data;
                  console.log(submitQuestions);
                  })
                  
 .catch((e)=> {console.log(e)})
 
 }
 
 // or using async/await
 const funcWithAsync = async () => {
    try {
        const submitQuestions = await Axios.post('https://hookahsite-backend.herokuapp.com  || https://localhost:8000 ' , custData);
        console.log(submitQuestions);
    }
    catch (e) {
      console.log(e);    
    }
 }

  • Related