What could be causing the page to refresh each time a POST request is submitted?

After sending a POST request to the local json-server-auth database, there is an issue with the page reloading. Is there a way to prevent this from happening? I am concerned about losing data due to the page refresh.

<form class="form">
        <input type="email">
        <input type="password">
        <button>Register</button>
</form>
<code lang="javascript">

const form = document.querySelector('.form')

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

   let data = {
      email: e.target[0].value,
      password: e.target[1].value
    }
    
    let res = await fetch('http://localhost:8080/signup', {
       method: "POST",
       headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
     })
     let json = await res.json()
     console.log(json)
     return false
})


I tested the code in Codepen and didn't experience any page reloads, but when using Live Server in VS Code, the page refreshes upon sending the request from the browser.

Answer №1

As mentioned by @Nico, if you swap out the "code" tag with <script>, everything will function as intended:

<body>
<form class="form">
    <input type="email">
    <input type="password">
    <button>Register</button>
</form>
</body>
<script>

const form = document.querySelector('.form')

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

   let data = {
  email: e.target[0].value,
  password: e.target[1].value
}
// To simplify testing, I've substituted your sign-up URL with a publicly available API:
let res = await fetch('https://jsonplaceholder.typicode.com/users', {
   method: "POST",
   headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
 })
 let json = await res.json()
 console.log(json)
})
</script>

Answer №2

After some investigation, I discovered the culprit - Live Server in VS Code. It turns out that whenever a request is sent to my local bd.json file, Live Server automatically refreshes the page. To fix this issue, I simply added db.json to the ignore list, and now everything is working smoothly.

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

Steps to indicate a selected check column in a grid

I am working with a grid that has a check column, and I need to programmatically mark the checkbox. This is how the check column is coded: columns: { items:[ { itemId: 'checkColumn', xtype: 'selectallche ...

Angular URL changes causing template flickering

Currently, I am in the process of developing a small application using Angular, but I am encountering an issue with template flickering. This problem occurs when one template is displayed briefly and then immediately switches to another. In my base templa ...

What is the best way to link an image in a React Component NPM module?

I have developed a date picker component in React and I'm currently working on uploading it to NPM. The component utilizes an external SVG file, but I am encountering issues with referencing that SVG file properly. Here's the structure of my fil ...

Apply styles specifically to elements that contain a child element

I have a scenario where there are multiple <p> elements with the same class names, but only one of them has a child element. My objective is to highlight only the <p> that contains a child, however, my current code ends up highlighting all of t ...

Rendering cannot occur because the data has not been set

var DialogController = function ($scope, configFac, $q) { var placeholders = []; var varInit = function () { $q.all([configFac]).then(function (response) { $scope.configResources = response[0]; placeholders[0] = resp ...

Input the chosen icon list values into a designated box

As a beginner in the world of Javascript, I am venturing into creating a password generator that involves using icons. The concept is simple - by clicking on any number of icons from a list, the corresponding hex code will be displayed in an input box. The ...

Assign a unique HTML attribute to a child element within a Material-UI component

Currently, I am trying to include the custom HTML5 attribute "data-metrics" in the span element within the ListItemText Material UI component. However, I am facing some difficulty achieving this as per the specifications outlined in the Component API Docum ...

How do you loop through specific <option>s within a <select multiple> element?

Although there are many questions on this topic, none seem to address the particular issue I am facing. My question is about iterating through only the selected options in a <select> element where multiple selections are allowed. How can this be ach ...

retrieve list of token ownership for an ERC20 contract

Currently, I am in the process of constructing a node.js server that utilizes web3.js to retrieve a map containing all accounts holding a specific token and the quantity of that token each account possesses. The desired output format involves the address s ...

Failed to retrieve JSON information from the server

Issue with Retrieving Data from Server: I am facing a problem where I have the value in my textview based on a condition set in the onCreate() method. However, when I remove this condition, the data retrieval from the server works perfectly fine for me (me ...

Is it better to store CSS and JavaScript in separate files or within the main HTML document

While the best practice is to place JavaScript and CSS code in separate files (such as .js and .css), many popular websites like Amazon, Facebook, etc. often include a large portion of their JavaScript and CSS code directly within the main HTML page. Whic ...

Do the items appear on screen only once you start typing in AngularJS?

Most things are working well except for a couple of issues Code var app = angular.module("MyApp", []); app.filter('offset', function() { return function(input, start) { start = parseInt(start, 10); return input.slice(start); }; } ...

The specified function 'isFakeTouchstartFromScreenReader' could not be located within the '@angular/cdk/a11y' library

I encountered the following errors unexpectedly while working on my Angular 11 project: Error: ./node_modules/@angular/material/fesm2015/core.js 1091:45-77 "export 'isFakeTouchstartFromScreenReader' was not found in '@angular/cdk/a11y&a ...

Prevent User from Leaving Until Postback Occurs (Implementing in Javascript/ASP.NET)

I have a few functions that run during postback, and they can sometimes take a bit of time to finish. When a postback is triggered, I display a loading image using the following code: function showLoader() { document.getElementById("<%=loadingImag ...

Having difficulty retrieving a value from a Json key

When attempting to retrieve an object from Mongoose, I encounter an issue where accessing the JSON object by key returns undefined. User.find({name: 'auth'},function (err,obj) { var authCode = JSON.stringify(obj); console.log(authCode); ...

Troubleshooting a malfunctioning Qwik-react calendar plugin, specifically the '@aldabil/react-scheduler' component, that is currently displaying but not working as expected. What

Having trouble with the Qwik-react Scheduler. Trying to integrate the "@aldabil/react-scheduler" react plugin into my qwik app using qwik-react, but encountering an error. The calendar appears on the page, however, the functionality does not seem to be wor ...

Utilizing JSON for effective data storage in database design

In my database, I have a list of campsites. The main table, tblSites, holds unique data such as name, coordinates, and address. It also includes columns for each facility (Toilet, Water, Shower, Electric) where 1=Yes and Null=no. Search queries would look ...

jquery ajax does not receive the returned data

I am working on a jQuery AJAX script $.ajax({ type: "POST", url: "register.php", data: "name=" + name + "&email=" + email + "&password=" + password + "&confirm_password=" + confirm_password + "&captcha=" + captcha, success: ...

Flagging Core Data entries as Favorites in SWIFTUI

I am currently developing an application that saves posts from online JSON to CoreData for offline access. The app is centered around Real Estate Listings, where users can buy and rent properties. So far, I have managed to store fetched listings in CoreDa ...

Invalid component exception: The element type is not valid in React Native

In my React Native App.js file, I have included the following code snippet import { StatusBar } from 'expo-status-bar'; import React, { useRef } from 'react'; import { StyleSheet, Text, View, Canvas } from 'react-native'; impo ...