Search code examples
javascriptexpressxmlhttprequest

Why is my POST request triggering express get


My express server, the deliverCard() method delivers a few key/value pairs.

app.get('/', (req, res) => {
  let card = deck.deliverCard();
  console.log('get', card)
  res.render('layout.ejs', {element:card});
});

app.post('/', (req, res) => {
  let card = deck.deliverCard();
  console.log('post', card);
  res.json(card);
});

The XMLHttpRequest:

  function updateCard(value) {
  let request = new XMLHttpRequest();
  let params = JSON.stringify({learned: value});

  request.onreadystatechange = () => {
    if (request.readyState === 4 && request.status === 200) {
      // Do a thing.
    } else {
      console.log('Status ' + request.status + ' text: ' + request.responseText);
    }
  }
  request.open('POST', '/', true);
  request.setRequestHeader('Content-type', 'application/json');
  request.send(params);
}

close.addEventListener('click', function() {
  value = checkbox[0].checked;
  updateCard(value);
});

I'm getting back the proper request body from the request, but for some reason, on the server side, the get callback function is being called.

Starting and initial page load:

app listening on port 3000!
get { name: 'div',
description: 'Defines a generic block of content, that does not carry any semantic value. Used for layout elements like containers.' }

On request:

post { name: 'meter', description: 'Defines a horizontal meter.' }
get { name: 'progress', description: 'Defines a progress bar.' } 

It's as if the page is reloading after receiving the response.


Solution

  • Once I got the question correct I found this answer:How to avoid automatic page reload after XMLHttpRequest call?. What is not obvious from my code above is that there's a form I'm submitting. In order to prevent the default action from a form submission, I did this:

    close.addEventListener('click', function(e) {
      e.preventDefault();
      value = checkbox[0].checked;
      updateCard(value);
    });