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

Restrict Text Input Field to Accept Only Specific Domain

Hey there! I've set up a text input box for users to link their Tripadvisor page to their profile. I want to make sure that when they paste the URL in, it is checked for the correct format. For example, if someone pastes: or , then allow the link. Ho ...

Having difficulty coming back from a promise catch block

I'm struggling to populate a menu list from my PouchDB database because I am unable to retrieve anything within the promise that is executed after calling get on the db. Below is the code in question: <MenuList> {this.populateSavedClues()} ...

The dropdown div does not activate when the image is clicked

When the image in the simple dropdown is clicked, it fails to activate the dropdown feature. This issue was encountered while working on a Shopify project, making it challenging to troubleshoot. To demonstrate the problem, I have re-created the scenario i ...

Enhancing audio control features using HTML and JavaScript

After utilizing various suggestions, I have successfully created a basic audio slider that starts playing sound (at zero volume) when clicked by the user. They can then adjust the volume as needed. My only challenge is that the volume adjustment only occu ...

Using AngularJS to retrieve JSON data with the HTTP module

I am a beginner in the world of angularjs and I need some guidance. Below is the code I have written: <!DOCTYPE HTML> <html ng-app="myapp"> <head> <meta charset="utf-8"> <title>Angularjs project</title> <script type= ...

Serve an image in Node.js from a location outside of the public folder

Is there a way to display an image that is located outside of the public folder in my webroot? Here is my directory structure: Webroot --core ----views ----public <- Stylesheets and other images are stored here ------index.ejs <- I want to display f ...

renewing a div element without the need to reload the entire webpage

I'm currently developing a setup process for configuring a database. My goal is to allow the user to progress through each phase without having to refresh the page. However, I've encountered an issue while trying to implement the .load() function ...

Error: The OOP class value for translateX in the Web Animation API is returning as undefined

I'm currently working on a basic animation project using JavaScript. I have utilized the Animation class from the Web Animation API. My goal is to create multiple instances of this class in order to animate different elements with varying values and r ...

What is the proper way to include 'rowspan' specific CSS within an HTML table?

I have an HTML table with rowspans in it: table tr, td { border: 1px solid black; } tr:nth-child(1) { background-color: red; } tr:nth-child(2) { background-color: blue; } <table> <tr> <td rowspan=2>Section 1</td> ...

Guide to swapping images on button click in HTML with dynamically changing image URLs retrieved from the server

I am a beginner in client-side scripting and new to Stack Overflow. I am looking for guidance on how to change an image within a div element upon clicking a button or anchor tag. Here is the code snippet I have written to achieve this: $scope.captchaCha ...

Tips on calculating the combined value of price and quantity simultaneously

Greetings, kindly bear with me as my knowledge of JS scripting is quite limited. My expertise lies more in PHP programming. I stumbled upon this neat and straightforward script that calculates the total of product table rows and also provides the grand t ...

Resize a div within another div using overflow scroll and centering techniques

Currently, I am working on implementing a small feature but am facing difficulties with the scroll functionality. My goal is to zoom in on a specific div by scaling it using CSS: transform: scale(X,Y) The issue I am encountering lies in determining the c ...

Route.get() is looking for a callback function, but instead received an [object Promise]

Currently, I am in the process of developing a REST API using express and following the architecture outlined in this particular article. Essentially, the setup involves a router that calls a controller. Let me provide you with an example of how a call is ...

The error message displays "window.addEventListener is not a function", indicating that

Recently, I've been dealing with this code snippet: $(document).ready(function(){ $(window).load(function() { window.addEventListener("hashchange", function() { scrollBy(0, -50);}); var shiftWindow = function() { scrollBy(0, - ...

Convert HTML to PDF and ensure that the table fits perfectly on an A4

I am currently utilizing html-pdf to convert my table data into a PDF format. The issue I am facing is that the table content exceeds the specified A4 paper size in such a way that two columns are completely missing in the generated PDF. However, when I c ...

Emulate a link click using key input

Hey there! I have this link example: <a href"http://google.es">Link</a> I'm wondering if it's possible to use JavaScript or a similar tool so that when I press a specific key, like the number 5 on the keyboard, it acts as if I click ...

Attempting to create a school project involving pizza, but encountering some technical difficulties

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>pizza ...

Unable to declare a string enum in TypeScript because string is not compatible

enum Animal { animal1 = 'animal1', animal2 = 'animal2', animal3 = 'animal3', animal4 = 'animal4', animal5 = 'animal5' } const species: Animal = 'animal' + num Why does typescr ...

Although AJAX $.post functions properly in the View, it seems to encounter issues when relocated to a separate .js file. Interestingly, all other JQuery functions work

I have recently delved into MVC, JQuery, and AJAX, and encountered a perplexing issue. After completing the initial development of a practice website, I dedicated time to enhance the interactivity using JQuery. Everything was functioning smoothly until I ...

Crafting jQuery Plugins with Object-Oriented Programming

Curious about the latest techniques for creating jQuery Plugins? There are so many different methods out there, it's hard to know which one is most effective. Could you recommend any helpful resources or templates for developing jQuery Plugins using ...