0

I was able to get a form working when using pug as the view engine with Express.js. But when I tried to use React, I have not been able to get form handling to work properly.

// Component.js
  </React.Fragment>
         // API_POST_URL=http://localhost:4000/api/donate
      <form action={process.env.API_POST_URL} method='post' id='testForm'> 
        <input type="hidden" name='step' value='3' />
        <button type='submit'>Post Test form</button>
      </form>
  </React.Fragment>

.

// index.js in another project folder
router.post('/api/donate', (req, res, next) => {

 // code testing for earlier steps removed

 else if (req.body.step === '3') {
      res.json({ message : "here's a response back"});
  }
});

The front end runs on port 3000, the back end on port 4000. Connecting the projects together incorrectly may be the issue. Routing is another possibility.

I have been able to receive a response object using Postman requests to the ENV variable URL above (http://localhost:4000/api/donate)

1 Answer 1

1

You code will make page refresh and you will loose the state of application which is not the goal of SPA's.

You can do this way:

</React.Fragment>
  <form onSubmit={submitFormHandler()}> 
    <input type="hidden" name='step' value='3' />
    <button type='submit'>Post Test form</button>
  </form>

Store above field in component state and pass it to submitFormHandler()

Use axios to submit form using http.

submitFormHandler = (data) => { axios.post('http://localhost:4000/api/donate',data);}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.