Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

The Fetch API is a powerful native API for these types of requests. You may have heard that one of the benefits of the Fetch API is that you don’t need to load an external resource in order to use it, which is true! Except… that it’s not fully supported yet, so you will still need to use a polyfill.

There are also some gotchas when working with this API, which is why many prefer to use axios for now. This may very well change in the future though.

Let’s check out a basic example of fetching a JSON file using fetch API:

fetch('https://api-url.json')
.then(function(response) {
  // Response comes here
})
.catch(function(error) {
  console.log('Found error: \n', error);
});

 

Example 2:

fetch('https://api.github.com/gists', {
    method: 'post',
    body: JSON.stringify(opts)
  }).then(function(response) {
    return response.json();
  }).then(function(data) {
    ChromeSamples.log('Created Gist:', data.html_url);
  });

 

Pass the API URL in the fetch() method to get the response from the webserver. You can handle the server response in the then and catch block.

Example:

<template>
  <div>
    <ul class="test-list" v-for="user in usersList" :key="user.id">
      <li class="test-list--item">
        <strong>{{ user.name }}</strong> <br>
        {{ user.email }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      usersList: []
    };
  },
  mounted() {
    fetch("https://jsonplaceholder.typicode.com/users").then((res) => {
          return res.json();
      }).then((users) => {
          this.usersList.push(...users);
      }).catch(error => {
          console.log(error)
      }) 
  }
};
</script>

 

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal and Laravel.

Web Posts

Search

Page Facebook