0

I'm littlebit confused about the fetch function, this is my code:

<template>
  <!-- above the fold -->
  <section class="uk-section uk-section-primary">
    <div class="uk-container">
      {{ items }}
    </div>
  </section>
  <!-- end above the fold -->
</template>

<script>
// @ is an alias to /src

export default {
  name: 'Home',

  data() {
    return {
        items: {}
    }
  },

  mounted() {
    this.getInfo()
  },

  methods: {
    getInfo() {
      fetch('mydomain.net/cockpit/api/singletons/get/frontpage' , {
        headers: { 'Authorization': 'Bearer xxmySecretxx' }
      })
        .then(res => this.items = res.json())
        .then(res => console.log(res));
    }
  },

}
</script>

In console.log I can view the items value, but on the browser the result is [object Promise] how fetch() works?

1

2 Answers 2

3

res.json() is an async function as fetch; this is why you add the second "then". if you edit the code like below, you will get what you need:

    getInfo() {
      fetch('mydomain.net/cockpit/api/singletons/get/frontpage' , {
        headers: { 'Authorization': 'Bearer xxmySecretxx' }
      })
        .then(res => res.json())
        .then(res => this.items = res);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

In a very simple manner all you really do is call fetch with the URL you want, by default the Fetch API uses the GET method, so a very simple call would be like this:

fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
    // Your code for handling the data you get from the API
})
.catch(function() {
    // This is where you run code if the server returns any errors
});

The fetch() method is modern and versatile. It’s not supported by old browsers, but very well supported among the modern ones.

The basic syntax is:

let promise = fetch(url, [options])

url – the URL to access.

options – optional parameters: method, headers etc.

Without options, that is a simple GET request, downloading the contents of the url.

The browser starts the request right away and returns a promise that the calling code should use to get the result.

The promise rejects if the fetch was unable to make HTTP-request, e.g. network problems, or there’s no such site. Abnormal HTTP-statuses, such as 404 or 500 do not cause an error.

We can see HTTP-status in response properties:

status – HTTP status code, e.g. 200. ok – boolean, true if the HTTP status code is 200-299.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.