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

Angular and Express: Automatically redirecting to the previous page after user login

A question similar in nature can be found here, although not directly relevant to my situation. Within my Single Page Application, I am implementing PassportJS for user authentication. There are multiple routes that necessitate user login. The routing is ...

Can Node.js handle parsing this as JSON?

Attempting to parse a small API that returns somewhat invalid JSON. Trying the following approach: var request = require('request'), url = 'urlhere'; request({ url: url }, function(error, response, body) { ...

Utilize AJAX or another advanced technology to refine a pre-existing list

I am trying to implement a searchable list of buttons on my website, but I haven't been able to find a solution that fits exactly what I have in mind. Currently, I have a list of buttons coded as inputs and I want to add a search field that will filte ...

transfer to a different outlet when needing to circle back earlier

I'm currently working on implementing validation in a form, and one of the needed validations involves retrieving a value from an input field and checking its existence on the server or in a JSON file. However, there seems to be a problem where even ...

The error message reads: "Node.js - Error: the path must either be absolute or specify root in order

I'm currently troubleshooting the root cause of this issue. Despite following instructions on this resource, I am encountering an error. TypeError: path must be absolute or specify root to res.sendFile at ServerResponse.sendFile (/Users/apple/Documen ...

What is the best way to have a text field automatically insert a hyphen after specific numbers?

Is there a way to make a text field insert hyphens automatically after certain numbers? For example, when typing a date like 20120212, could we have the input automatically formatted with hyphens after the first 4 digits and the second two, so it displays ...

By using Yii2, you can pass an id to the URL by simply clicking on a

I am struggling with sending the post_id from a div containing text content (retrieved from a database) to a URL in order to render a view page displaying the entire content. I am using Yii2 and believe I need to use JavaScript for this task, but I am unsu ...

Creating a simple NodeJS application - Handling 404 errors

I'm currently following a tutorial that covers role-based authentication with Passport in Ionic 2. Here is the link to the tutorial: However, I am facing an issue when trying to access the following URLs on my browser: http://localhost:8080/ http: ...

The output from the NodeJS storage module function

Attempting to implement Two-Factor Authentication in my initial NodeJS project, which serves as a learning tool for Node. While the function correctly retrieves values from data_url, when I assign it to a variable and return data_url, it returns 'und ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Ways to remain on the same page even after submitting a form

I've been searching for a solution to my specific issue for days, but haven't had any luck. Can anyone provide assistance? I have a form on my website that is supposed to send an email when clicked, while also converting the div from a form to a ...

Struggling to Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...

Explore the power of Infinity.js for optimizing the rendering of large HTML tables, complete with a detailed example using prototype

Is there a way to efficiently load/render large html tables without compromising performance, especially in Internet Explorer? I recently came across a plugin in prototype.js (https://github.com/jbrantly/bigtable/, post: , demo:) that addresses this issue ...

Is there a way for me to manually designate certain domains with the rel="follow" attribute while assigning all other external links with the rel="nofollow" attribute?

I'm working on developing a community platform similar to a social network. I've implemented a code that automatically makes all external links nofollow. However, I would like to create a feature that allows me to remove the nofollow attribute f ...

The leaflet.js library threw an error: LatLng object is not valid due to invalid coordinates (NaN, NaN)

Currently, I am working with a JSON file that contains coordinates in pairs. "_id" : ObjectId("59407457838b932e0677999e"), "type" : "MultiPoint", "name" : "points", "coordinates" : [ [ -73.958, 40.8003 ], ...

When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf. The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution. 1) When the current elem ...

Unable to eliminate user registration feature with Meteor and React

Exploring the world of Meteor and diving deep into its functionalities, I am currently focused on creating a user login and signup page with personalized control panels for each registered user. Although I have successfully implemented the signup and logi ...

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

Exploring the Utilization of FormData and form.serialize within the Data Parameter of Ajax Jquery

My form includes a multiupload uploader for files, structured like this : <div class="col-md-4"> <div class="form-group"> <label class="control-label col-md-3">Location</label> <div class="col-md-9"> <?php ...

Are there any more efficient methods to retrieve an object from an arrow function in TypeScript?

Trying to retrieve an object from an arrow function is posing a challenge for me, especially with the following function f: myMethod(f: data => { return { someField: data.something }; }); I am aware that for simple types, you can condense the arrow ...