Why does my POST request result in an express get being triggered?

When my express server runs the deliverCard() method, it sends a set of 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);
});

Regarding the use of XMLHttpRequest:

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

  request.onreadystatechange = () => {
    if (request.readyState === 4 && request.status === 200) {
      // Perform an action.
    } 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);
});

The issue I'm facing is that although I receive the correct request body, the get callback function is triggered on the server side after receiving the response.

Here are the events during the 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.' }

Upon a request being made:

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

It seems like the page is reloading after receiving the response.

Answer №1

After successfully solving the problem, I came across a helpful solution at How to prevent automatic page reload after making an XMLHttpRequest call?. What may not be immediately apparent from my code snippet is that there is a form being submitted. To prevent the default action of a form submission, I implemented the following:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring mouse events from iframes to the parent document

Currently, I have a situation where my iframe is positioned over the entire HTML document. However, I am in need of finding a way to pass clicks and hover events from the iframe back to the main hosting document. Are there any potential solutions or alter ...

Unable to use OrbitControls with Node 12's ES6 import functionality

Currently, I am working with Node 12 (experimental-modules) and using npm for three.js. However, I'm facing issues with Imports when trying to include OrbitControls.js in my project. My index.js file is set as "script: module". Unfortunately, none of ...

Steps for adjusting button size in Sencha Touch

How can I resize a button in Sencha Touch 2 to make it smaller? I need to change its height. Any sample code you could provide would be greatly appreciated! Thanks navigationBar: { items:[{ xtype: 'button', ...

Using JSON to create bootstrap styled link buttons

My current code is functioning well with links. However, when I try to use a bootstrap button instead of a regular button, the button appears in the table but no longer directs to the link. var button = "<button class='btn btn-inf ...

Change ES6 JavaScript to ES5 standard

Is there a way to transform this code snippet from other questions into ES5 format? I am attempting to extract data from a JSON array. var match = function(query, input) { return input.filter(function(entry) { return Object.entries(query).every(fun ...

Issue with updating arrays in Mongoose not functioning as expected

Attempting to update values involves finding the object, pushing a value into 2 arrays, and then updating the original value. Although the object is found and values are successfully pushed, the update function fails to detect the changes, resulting in an ...

Is it possible to manually input values when printing a PDF instead of pulling them from the main HTML?

I am facing a challenge in adding a "Print PDF" option to my website because it is built using Ext.js, and therefore the code is not in HTML. Despite searching for ways to print a PDF from the site, all solutions I found involve using HTML. Is there any li ...

Leveraging JQuery to retrieve the string value from an onclick() event

Curious if there's a more efficient approach to tackle this issue, decided to seek input from the SO community... There's a third-party web page over which I have no control in terms of how it's displayed, but they do allow me to integrate ...

Issue communicating with connect-flash: flash variable is not recognized

I've been diving into books on node.js, express, and mongodb lately. In one of the examples, the author showcases the usage of connect-flash. However, I'm encountering some difficulties getting it to function as expected. Below are snippets from ...

Stop allowing users to place periods before their nicknames on Discord servers (Programming in discord.js with a Discord Bot)

I have been working on a script to identify when a user alters their name on Discord by adding a period at the beginning, such as changing "bob" to ".bob". The goal is to prevent this change and keep it as "bob". if (user.nickname.startsWith(".")) { ...

What is the best method for creating a top margin that is dependent on the height of the browser?

Is there a way to make the CSS margin: top; on my HTML main_content element relative to the browser window? I want the main_content to always stay at the bottom of the browser window. How can I achieve this? I attempted the following code, but it didn&apo ...

Bot on Discord engaging in a gaming session

I recently developed a Discord bot with the status of ""playing a game"" and here is the code that I implemented: bot.on('ready', () => { console.log('Client is online!'); bot.user.setActivity('osu!'); Th ...

Leveraging AngularJS html5mode in conjunction with express.js

Client-side: when("/page/:id", { templateUrl: "partials/note-tpl.html", controller : "AppPageController" }); $locationProvider.html5Mode( true ); Html: <a ng-href="/page/{{Page._id}}">{{Page.name}}</a> Server-side: app.use("/pag ...

Unable to Pause Video with Javascript

I have a project with a video that plays in a continuous loop. Below is the HTML code for the video tag: <video playsinline autoplay muted loop id="myVid"> <source src="River.mp4" type="video/mp4"> </video> My goal is to make the vi ...

Deciding when to utilize an interface, when to avoid it, and when to opt for a constructor in Typescript for the creation of JavaScript arrays

Exploring the concept of JavaScript object arrays in TypeScript In my current project, I am retrieving a JSON array from an observable. It seems that I can define and initialize the array without necessarily specifying an interface or type. let cityList[ ...

NodeJS/ExpressJS Image Redirection

Would it be acceptable for an img to have a src value that redirects to another page? In my view, I am using the following img tag: <img src='/images/fileName'/> In app.js app.get('/images/:fileName', subject.image); Here is ...

Issue with ajax form: success function is not functioning as intended

For my form submission, I am utilizing ajaxForm(options) to run some functions before submitting the form. Here is an example of the options that I have configured: var options = { target : '#output1', success : ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

When viewing on mobile devices, the hover effect in responsive web design

While working on a responsive website, I encountered some challenges. I have a Div containing an image and some information. When a user hovers over this div, the background changes and 3 buttons appear. However, the issue arises when using a mobile devi ...

Utilizing socket.io and Express.js in conjunction with IISNode: A Comprehensive Guide

I've recently configured a Windows 2012 r2 server with IIS, IISNode, and the Rewrite module. Everything seems to be working seamlessly so far. Basic applications using Express also work without any issues. However, as soon as I integrate socket.io int ...