[Vuejs]-Display data in promise call with vuejs and fetch()

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/c**kpit/api/singletons/get/frontpage' , {
        headers: { 'Authorization': 'Bearer xxmySecretxx' }
      })
        .then(res => res.json())
        .then(res => this.items = res);
    }
👤salihtopcu

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.

👤Maxim Kogan

Leave a comment