What could be causing the page to refresh every time a post or update is made using a mock REST API with JSON

I have been using Json-Server to mock API requests, but I'm facing an issue where the page reloads every time I fetch or update a post. I've tried searching for a solution, but haven't found one yet.

Interestingly, even though I followed a JavaScript tutorial and our codes were identical, the page did not refresh on the instructor's side but it does on mine.

class EasyHTTP {

  async post(url,data){
    const response = await fetch(url,{
                                      method: 'POST',
                                      headers:{'content-type':'application/json'},
                                      body: JSON.stringify(data)
                                    });
    const resData = await response.json();
    if(resData){
      return resData;
    }else{
      await Promise.reject(new Error('ERROR: Dont Know'));
    }
  }
}

const http = new EasyHTTP();

// Submit POST
document.querySelector('.post-submit').addEventListener('click',submitPost);

function submitPost(e){
  e.preventDefault(); 
   //e.stopPropagation(); 
  const title = document.querySelector('#title').value;
  const body = document.querySelector('#body').value;

  const data = {
    title,
    body
  };

    http.post('http://localhost:3000/posts',data)
    .then(res => {
      console.log(res);
    })
    .catch(err => console.log(err));
}
       <input
            type="text"
            id="title"
            class="form-control"
            placeholder="Post Title"
          />
  <textarea
            id="body"
            class="form-control"
            placeholder="Post Body"
          ></textarea>
<button  class="post-submit">Post It</button>

It's frustrating as I keep trying to resolve the issue with the page reloading each time I fetch a post. Any help would be greatly appreciated.

Answer №1

After some troubleshooting, I discovered the fix for my issue. Since I was utilizing VS Code, I decided to deactivate the live-server extension, and lo and behold, everything is now functioning smoothly without any need for refreshing.

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

Having trouble with my Express app due to errors popping up because of the order of my routes

app.get('/campgrounds/:id/edit', async (req,res) =>{ const campground = await Campground.findById(req.params.id) res.render('campgrounds/edit', { campground }); }) app.get('/campgrounds/:id', async (req,res) =>{ ...

TypeScript's type assertions do not result in errors when provided with an incorrect value

We are currently using the msal library and are in the process of converting our javaScript code to TypeScript. In the screenshot below, TypeScript correctly identifies the expected type for cacheLocation, which can be either the string localStorage, the ...

Steps to forward a restricted user to a specific webpage

I am currently utilizing NextJs and am in the process of creating a redirecting function for users who have been banned or blocked from accessing the DB/session. My attempt at this involved: redirect.js, where I created a custom redirect function. impo ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

What is the process of using a For loop to output a string in reverse order?

I'm attempting to reverse the string "hello" using a For loop, aiming for the output of "olleh". However, I'm facing an issue where the last character in the string is not being removed after being added to the array. Consequently, only the last ...

How should I manage objects that are passed by reference in the context of functional programming?

Lately, I have been experimenting with some code in an attempt to delve deeper into functional programming. However, I seem to have hit a snag. I am struggling with handling an object. My goal is to add key-value pairs to an object without reassigning it, ...

The value is not getting set after calling React Hook UseState

I am currently working on a React component that handles payment processing. There is a part of my code where I utilize the useEffect hook alongside useState to set certain values. Check out the code snippet below: React.useEffect(()=>{ axiosFetch ...

Remove an item from an array and keep it stored efficiently without generating unnecessary waste

I'm interested in finding a high-performance method for removing and storing elements from an array. My goal is to create an object pool that minimizes the need for garbage collection calls. Similar to how .pop() and .unshift() remove elements from a ...

What is the presence of the term "sort" in this JSON document from elasticsearch?

While working on indexing data into Elasticsearch, I encountered a puzzling issue related to the appearance of the ""sort"" attribute. Interestingly, this attribute was not included in my mapping nor in the data being indexed. This instance prom ...

Simplify your bootstrap Input field code by utilizing components or a similar method in Vue.js

Using a single file component with a pug template, I am faced with multiple input fields that have the same formatting. Here is an example: .input-group.input-group-sm .input-group-addon Purchase Price input.form-control(v-model='purchase_ ...

What is the correct way to iterate through a list of images fetched with getStaticProps and display them within the same component?

What is the proper way to map a list of images returned using getStaticProps? I had successfully implemented this by passing a prop to the gallery component in another page. However, I now want to consolidate all the getStaticProps code within the gallery ...

Is it possible to run concurrent PostgreSQL queries in NodeJS?

I'm unsure why, but the task is supposed to be run in parallel and should only take 2 seconds: const test = async () => { client.query("SELECT pg_sleep(2) FROM test", (err, result) => { console.log("DONE!"); }) client.query("SELECT pg ...

Exploration of jsTree capabilities

I am currently exploring the jsTree plugin API and I'm struggling to grasp where exactly the API functions like set_theme, show_dots, etc. should be applied. On this page, I noticed that some functions are preceded by jQuery, while others are precede ...

Leverage jq to combine keys that share the same identifier

Imagine having two JSON files: 'b.json' and 'a.json'. [ { "id": 3, "foo": "cannot be replaced, id isn't in a.json, stay untouched", "baz": "do not touch3" }, { "id": 2, "foo": "should be replaced with &ap ...

What is the best way to send AJAX post data to a Node.js server?

I am currently facing an issue with passing a unique ID object back to the server side using Ajax after making an API call. I need help figuring out what might be going wrong in my code. This is the client side code snippet where I loop through a JavaScri ...

How to troubleshoot Python errors (+mod_wsgi) using the Chrome Network panel

As a newcomer to Python, I am facing an issue with viewing error messages. The problem arises when a javascript function is making a call as follows: $.getJSON('test.py', {data: 'somedata'}, function(return){alert(return.echo)}) In th ...

Is there a way to create a dynamic CSS class without relying on the use of IDs?

Is there a way to create a dynamic CSS class without using an ID? $( "#mydiv" ).css( "width", $("#widthtextbox").val() ); $( "#mydiv" ).css( "height", $("#heighttextbox").val() ); I am looking to implement multiple CSS classes for this task. ...

Tips for updating routerlink in navigation bar in Angular 4

I'm encountering an issue with routing to the wrong routelink. How can I prevent this from happening? My apologies for my lack of experience. The error message displayed in the Chrome console is: ERROR Error: Uncaught (in promise): Error: Cannot mat ...

Encountered an unhandled rejection error: TypeError: Unable to destructure the property 'protocol' of 'window.location' because it is undefined

I integrated the react-tradingview-widget into my nextjs project and it was working perfectly on version 10.2.3. However, after upgrading to version 12.1.4, I encountered an error when trying to reload the tradingview component. The error message was: unh ...

"Attempting to send JSON data through Express resulted in an error due to

I have encountered an issue while trying to send JSON data to a node server using Express. Despite the fact that the JSON object is valid, the server keeps throwing an error stating 'unexpected token i'. Client Side Code: $.ajax({ contentTy ...