0

Assume that I have a form as such that is submitted to a POST route /example:

<form action="/example" method="POST">
  <input type="text" name="fname"><br>
  <input type="text" name="lname"><br>
  <button type="submit">Send</button>
</form>

app.js:

app.post('/example', (req, res) => {
  ... 
});

server.js

const app = require('./app');

app.listen(3000, () => {
    console.log('server is running on port 3000');
});

Does Javascript provide a way to prevent the form submission if the server disconnects in order to prevent the website from crashing?

I have searched online but couldn't find any such solutions to this problem.

bgmn
  • 498
  • 2
  • 7
  • 25
  • 1
    You could submit the form via AJAX and catch/handle various errors/failures in the client-side code. – David Apr 20 '20 at 13:50
  • Would server disconnection pass as an error if I try to ```catch```? – bgmn Apr 20 '20 at 13:52
  • If by "server disconnection" you mean that the server doesn't respond then I imagine that would result in some kind of identifiable error. It depends on how you're using AJAX, such as what client-side library you may be using or just manually using it. However you're using AJAX, you can find examples of how to handle errors and then start testing that specific error. – David Apr 20 '20 at 13:54

1 Answers1

2

You can do it but will have to be done programmatically and not implicitly through the action attribute. For that, you can use then/catch from Promises or try/catch with async/await like the example below:

<form>
      <input type="text" name="fname" />
      <br />

      <input type="text" name="lname" />
      <br />

      <button type="submit">Send</button>
    </form>

    <script>
      const form = document.querySelector('form');

      form.addEventListener('submit', async (event) => {
        event.preventDefault();

        const elements = event.target;
        const firstName = elements['fname'].value;
        const lastName = elements['lname'].value;
        const dataToSend = { firstName, lastName };

        try {
          const response = await fetch('/example', {
            method: 'POST',
            body: JSON.stringify(dataToSend),
            headers: { 'Content-Type': 'application/json' },
          });
          const data = await response.json();

          console.log('Data returned from the server', data);
        } catch (error) {
          console.log('Uups! Something went wrong', error);
        }
      });
    </script>
lndgalante
  • 402
  • 2
  • 4
  • Am I right in thinking that ```firstName``` would be accessed in node.js by using ```const firstName = req.body.firstName;```? – bgmn Apr 20 '20 at 14:09
  • I seem to be getting ```{}``` i.e. firstName and lastName are ```undefined``` when doing ```console.log(req.body)``` in the app.js file inside the POST route. – bgmn Apr 20 '20 at 14:26
  • Yes you're right you access those variables through the body. You will need body-parser middleware. – lndgalante Apr 20 '20 at 18:43
  • I'm using ```app.use(bodyParser.urlencoded({ extended: true }));``` but still getting it as undefined for some reason :/ – bgmn Apr 20 '20 at 18:52
  • 1
    That should do the work, are you executing it before your endpoint definitions?, I'll suggest creating another question for that case. – lndgalante Apr 20 '20 at 20:25
  • I have posted this problem on https://stackoverflow.com/questions/61331623/json-isnt-getting-sent-through-to-ajax-post-request . Thank you for your help! – bgmn Apr 20 '20 at 20:38