When an attempt to make a POST request using fetch() is made, a TypeError: Failed to fetch error is immediately thrown instead of

My front-end form is posting data using the fetch() function. Everything works fine and I get the correct response from the server when it runs smoothly without any interruptions. However, when I debug the server endpoint, it throws a TypeError: failed to fetch error.

This issue is not related to CORS because the request is resolved properly once I remove the breakpoint from the API.

exports.add_new_data = async (req, res, next) => {
  promise = db.addData(req.body.data); //this is where I have the breakpoint and pause
  promise
    .then((data) => {
      res.status(201).send({
        success: true,
        message: "Data added successfully",
        error: null,
        data: data,
      });
    })
    .catch((err) => {
      res.status(500).send({
        success: false,
        message: err.message,
        error: err,
      });
    });
};

And here is the code for the frontend:


render() {
  return (
    <div>
      <form>
        <label htmlFor="Name">Name: </label>
        <input id="Name" type="Text" onChange={this.updateName} />
        <label htmlFor="Age">Age: </label>
        <input id="Age" type="Text" onChange={this.updateAge} />
        <button onClick={this.submit}>submit</button>
      </form>
    </div>
  );
}
submit = async () => {
  try {
    let data = [];
    data.push({ name: this.state.name, age: this.state.age });
    let res = await fetch(`${d}/people/add-person`, {
      // Error immediately thrown here
      method: "POST",

      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ data }),
    });
    let receivedData = await res.json();
    alert(`Status ${res.status}`);
    if (res.status === 200) {
      alert("Added Successfully");
    } else {
      alert(`${receivedData}`);
    }
  } catch (error) {
    alert(error);
  }
  alert(`Name: ${this.state.name} Age: ${this.state.age}`);
};

Answer №1

The problem stemmed from the page refreshing and interrupting the fetch request. By default, buttons in forms are set to submit type, which caused this behavior. To resolve this issue, the event parameter was added to the submission function and the preventDefault() method was used to prevent the page from refreshing.

 submit = async (e) => { //added parameter
        e.preventDefault();
        try{
            let data = [];
            data.push({name: this.state.name, age: this.state.age});
            let res = await fetch(`${d}/people/add-person`, {// Error immediately thrown here
                method: 'POST',

                headers: {
                    'Content-Type':'application/json', 
                },
                body: JSON.stringify({data})
            });
            let data = await res.json();
            alert(`Status ${res.status}`);
            if(res.status===200){
                alert("Added Successfully");
            }else{
                alert(`${data}`);
            }

        }catch(error){
            alert(error);
        }


        alert(`Name: ${this.state.name} Age: ${this.state.age}`);
    }

Another solution would be to simply change the button type to button

    <button type="button" onClick={this.submit}>submit</button>

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

Tips for executing an npm command within a C# class library

I am currently developing a project in a class library. The main objective of this project is to execute a JavaScript project using an npm command through a method call in C#. The npm command to run the JavaScript project is: npm start The JavaScript ...

How to effectively pass data between parent and child controllers in Angular 1 - Seeking guidance

Currently, I am working on two separate applications that have a common requirement of displaying active incidents and closed incidents. Both apps involve similar logic for creating, modifying, saving, and deleting incidents. I am exploring the best appro ...

React: Unexpected error occurs with invalid element type

I encountered the following issue while attempting to utilize a component Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forg ...

Using Mocha in Node to make XMLHttprequests

Currently, I am experimenting with using node-xmlhttprequest. Here is an example of what I have been working on: // f.js (function() XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest xhr = new XMLHttpRequest() xhr.open('GET ...

Leveraging Async / Awaits with Promise

Within my code, I have a specific promise chain that follows this structure: myPromise() .then(getStuffFromDb) .then(manipulateResultSet) .then(manipulateWithAsync) .then(returnStuffToCaller) An issue arises when working within the mani ...

Angular directive does not focus on the text box

I've been working on creating text boxes using a directive and I want only the first text box to be in focus. To achieve this, I am utilizing another directive for focus control. Below is my script: <script> angular.module('MyApp',[]) ...

"Enhancing security measures with multiple nonce for Content Security Policy

I am encountering an issue with my single page application, which is developed in .net core MVC 2.2. The application loads html sections on the fly. In the main document, I have added a Content Security Policy (CSP) policy with a dynamically generated hea ...

Tips for including shared information across different ionic tabs

Is there a way to include some shared content, like a canvas, in between the content of different tabs in Ionic? I want this common content to be displayed across all tabs, while each tab still shows its own dynamic data below it. I attempted to add the c ...

Discovering the method to extract a specific section from a lengthy string

Looking to extract phone numbers from an HTML source code using PHP? Each phone number in the code starts with 'phone=' and ends with %. For example, consider the following sample HTML code: b2e1d163b0b4dc6ebfa5&amp;t=s&amp;phone=9535503 ...

How can a list of objects in a JPA entity with a many-to-one relation to a data entity be sorted based on the result of a method call from the data entity?

In my JPA entity User, there is a OneToMany relation to a UserStats entity. I made changes to the code to use UserStats instead of storing victoryRatio directly in the User entity. Now, calculateVictoryRatio() method is implemented in the UserDetails entit ...

React's connect method is causing issues with my test case

Attempting to create a test case for my jsx file... Took a sample test case from another jsx file... The other file does not have the connect method... But this new file contains the connect method... Believe this is causing issues with my test case... Any ...

The presence of foreign collections does not appear to be reflected in the combined data

I am developing a basic forum and I'm looking to connect two databases so I can show information about the user who created a post on that post: User.js: _id:60ccb13a21d65f0c7c4c0690 username: testuser name: test And Createpost.js _id:60d80b1305dcc5 ...

Provide the option to assign values on select options in order to choose specific JSON data

When working with JSON data from an API, I am creating a dynamic select element. The goal is to change some content (text and image src) based on the option selected from this select element. I have successfully populated the select options with names usi ...

Type into the asp:TextBox and then click on my button, where it triggers a JavaScript function

So here's my issue: <asp:TextBox runat='server' /> <button id='b2'>hi</button> <script> $('#b2').click(function(e){ e.preventDefault(); alert('you clicked the button'); }); </script ...

Leveraging AJAX for transferring variable from a dynamic HTML table to PHP for executing an update query

Is there a way to insert a value into the input field valor and update the respective row with that value using both the ID and the valor in the update query? I seem to be missing something here, what could it be? Table <?php $IDTipoEquipamento = ...

Tips for obtaining and storing multiple inputs within the same readline.question prompt in separate variables

Seeking to gather multiple user inputs in a single readline question and assign them to different variables? You're not alone! Ran into this challenge myself while trying to figure out the solution. Code import * as readline from 'node:readline&a ...

Using Event Delegation in Practice

I am facing an issue with loading 2 <span> elements from separate ajax scripts onto a webpage upon selection from a dropdown box. Here is a snippet of my code: <span id='room_rate'>1,000</span> // content loaded by one ajax scri ...

When attempting to utilize res.sendfile, an error arises indicating that the specified path is incorrect

I am facing an issue with my Express.js server and frontend pages. I have three HTML and JS files, and I want to access my homepage at localhost:3000 and then navigate to /register to render the register.html page. However, I am having trouble specifying t ...

Tips for transferring objects from JavaScript/jQuery/angular to an action function

Issue at Hand: I currently have a form with 10 fields, and the challenge lies in passing these 10 values to an ASP.Net MVC Action. To tackle this, I utilize ng-click to send these values to the action which then forwards them to the database. I find myse ...

Access row information within a function while incorporating a data-table component

I am currently facing a challenge with my custom Data-Table being utilized by all developers in the workspace. Due to its complexity, I find it difficult to make changes for minor tasks and have decided to explore alternative solutions. The Data-Table is ...