简体   繁体   English

为什么我的POST请求触发快递获取

[英]Why is my POST request triggering express get

My express server, the deliverCard() method delivers a few key/value pairs. 我的快递服务器deliverCard()方法提供了一些键/值对。

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 : 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. 我从请求中恢复了正确的请求主体,但是由于某种原因,在服务器端,调用了get回调函数。

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. 好像页面在收到响应后正在重新加载。

Once I got the question correct I found this answer: How to avoid automatic page reload after XMLHttpRequest call? 找到正确的问题后,我会找到以下答案: 如何避免在XMLHttpRequest调用后自动重新加载页面? . 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM