← Back to all tutorials

HTTP Requests

Make HTTP requests from Vue using vue-resource or axios — fetch external data and integrate it into your Vue application.

HTTP Requests

Most real applications fetch data from APIs. In this episode you will learn how to make HTTP requests from Vue using an HTTP library to get and send data.

Choosing a Library

LibrarySizeNotes
vue-resourceSmallVue-specific, uses this.$http
axios~13KBFramework-agnostic, widely adopted, better error handling
fetchBuilt-inNative browser API, no install needed

We will use vue-resource for this series as it integrates directly with the Vue instance.

Installing vue-resource

npm install vue-resource
// main.js
import Vue from 'vue';
import VueResource from 'vue-resource';

Vue.use(VueResource);

After installing, every component gets access to this.$http for making requests.

Making a GET Request

export default {
    data() {
        return { blogs: [] };
    },
    created() {
        this.$http.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                this.blogs = response.body.slice(0, 10);
            });
    }
};

Making a POST Request

methods: {
    addPost() {
        this.$http.post('https://jsonplaceholder.typicode.com/posts', this.blog)
            .then(response => {
                console.log('Created:', response.body);
            });
    }
}

Key Takeaways

  • vue-resource adds this.$http to every component for HTTP requests
  • Use this.$http.get(url) and this.$http.post(url, data) for REST operations
  • Fetch initial data in the created lifecycle hook
  • Responses are promises — use .then() to handle the result