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
| Library | Size | Notes |
|---|---|---|
vue-resource | Small | Vue-specific, uses this.$http |
axios | ~13KB | Framework-agnostic, widely adopted, better error handling |
fetch | Built-in | Native 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-resourceaddsthis.$httpto every component for HTTP requests- Use
this.$http.get(url)andthis.$http.post(url, data)for REST operations - Fetch initial data in the
createdlifecycle hook - Responses are promises — use
.then()to handle the result