Updated April 3, 2023
Introduction to Vue.js Axios
Vue.js Axios is defined as an HTTP client request for the node and the browser. Axios can be done with simple JavaScript or React and Vue. Axios is an Excellent HTTP library that executes on both client and a server, which makes an API request, does the task to produce the result and specifies easier concepts to read and debug. Vue.js is the front-end JavaScript Framework to build tools and libraries. The Axios works well in the platform like node.js and browsers.
Vue.js Axios is a leading framework to Consume REST APIs is easy with them. Here all the example code is executed in Visual Studio Code with Node.js.
Syntax
The Structure is given as :
Using a Simple GET request
<template>
<div id= div>
beforeMount(){
this.getName();
},
methods:
</template>
<Script>
API Request:
;(async () => {
const response = await axios.get('https://')
console.log(response)
})()
How Axios works in Vue.js?
Vue lacks a built-in HTTP library, so Axios library is recommended to keep interaction with REST API. So here in this article, we have used JSON PLACEHOLDER API to take a few sample data for the application. Generally, Axios makes HTTP requests like GET, POST, PUT, DELETE. The methods includes axios.get() and axios.post().
Axios has good benefits like supports older versions of browsers, JSON package transformations, and supports the upload process.
The Following working Steps to be followed:
1. Installation- Axios
npm install axios
2. Creating Vue.js App to start vue CLI app
3. To install vue-Axios (HTTP Client), the following command is used:
npm install - - save axios vue-axios
The following sample code is reflected in main.js
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
4. To run a Vue app
npm run serve
This directs to http://localhost:8080
Installing Vue Dependencies
The next step is to create Components; it is done like src -> Components and adds the code inside the component files. Finally, the sample demonstration is given in Example 1.
To start an application, HTML declaration is done, which acts as a front-end UI.
Secondly, to perform Vue.js Component
Lastly, add API to the vue.js Component.
Key Points:
- To handle errors in the Axios library ‘catch’ method is preferred as we use this in case of any network failure while requesting data.
- Using the Loading indicator while the page takes too much time to the respond from the backend.
Examples of Vue.js Axios
In this section, we shall see how to use Vue.js and Axios together.
Example #1
Showing Simple Request Page
Code: App.vue
<template>
<div class="container">
<div class="justify">
<div class="col1">
<div class="card">
<div class="card-header">Vue Axios - EDUCBA.COM</div>
<div class="card-body">
<form @submit="formSubmit">
<strong>Name:</strong>
<input type="text" class="form-control" v-model="name">
<strong>Description:</strong>
<textarea class="form-control" v-model="description"></textarea>
<button class="button click">Submit</button>
</form>
<strong>Result:</strong>
<pre>
{{output}}
</pre>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted () {
console.log ('Component mounted.')
},
data() {
return {
name: '',
description: '',
result: ''
};
},
methods: {
formSubmit(e1) {
e1.preventDefault();
let currentObj = this;
this.axios.post('http://localhost:8000/yourPostApi', {
name: this.name,
description: this.description
})
.then(function (response) {
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
}
}
}
</script>
Next, this Java Script part shows the application Logic
main.js
import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
import Add from './components/Add.vue';
Vue.use(VueRouter);
const routes = [
{
name: 'Weseley',
path: '/add',
component: Add
}
];
const router = new VueRouter({ mode: 'history', routes: routes });
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
router
}).$mount('#app')
We have used mount () to the API to make a request, and the results are saved.
Add.vue
<template>
<div class="container">
<h1>Generate a Bill</h1>
<form v-on:submit.prevent="add">
<div class="row1">
<div class="col">
<div class="form1">
<label>Email:</label>
<input type="text" class="form-control" v-model="bill.email"/>
</div>
</div>
</div>
<div class="row1">
<div class="col">
<div class="form1">
<label>Bill Description:</label>
<textarea cols="4" rows="4" class="form-control col6" v-model="bill.description"></textarea>
</div>
</div>
</div><br />
<div class="form">
<button class="btn btn-primary">Generate a Bill</button>
</div>
</form>
</div>
</template>
<script>
export default {
data(){
return {
ticket: {}
}
},
methods: {
add() {
alert('clicked');
}
}
}
</script>
Creating Basic Vue Application by building an HTML Page by creating html in editor
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="shortcut icon" href="<%= webpackConfig.output.publicPath %>favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
<title>vue.js Axios Demo</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
Output:
Example #2
Fetching data from API’s through Vue.js Axios
Code: App.vue
<template>
<div>
<h1> <center> Fetching a data </center> </h1>
<ul>
<li v-for="(val, key) in post" :key="key">
{{ key }} : {{ val }}
</li>
</ul>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
post: null,
};
},
created: function() {
axios
.get("https://jsonplaceholder.typicode.com/posts/1")
.then(result => {
this.post = result.data;
})
}
};
</script>
Explanation: To do this, we have already created a project in Vue using Vue-CLI, and next is by installing the Axios library as shown in the above Screenshot. So this example fetches data from the JSON API, which is created already, and we get that request by .get () in the code. And now the output looks like this when you open a browser
Output:
Example #3
Fetching data from the third party.
Code: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">
<title>The Content Text app</title>
</head>
<body>
<div class="container" id="app">
<h3 class="text-center">Vue Content</h3>
</div>
<script src="https://unpkg.com/vue"></script>
<script src="app.js"></script>
</body>
</html>
App.vue
const vm = new Vue({
el: '#app',
data: {
results: [
{theme: "Hello World", abstr: "Norway is a Scandivian country"},
{theme: "Welcome Page", abstr: "Norway is a Scandivian country"},
{theme: "Home Page", abstr: "Norway is a Scandivian country"},
{theme: "End", abstr: "Norway is a Scandivian country"}
]
}
});
<div class="columns medium-3" v-for="result in results">
<div class="card">
<div class="card-divider">
{{ result.theme }}
</div>
<div class="card-section">
<p>{{ result.abstr }}.</p>
</div>
</div>
</div>
app.js
import Vue from 'vue'
import App from './App'
import axios from 'axios'
Vue.prototype.$http = axios
app = new Vue({
el: '#app',
components: { App },
template: '<App/>'
})
Output:
Conclusion
By now, we have understood the functionality of the application and the fundamentals. This article would be a pretty starting point to handle API calls in any application and helpful in future projects. Therefore, we have achieved here how to send an HTTP request to the Node.js and fetches respective data from the database.
Recommended Articles
This is a guide to Vue.js Axios. Here we discuss the introduction, syntax, and working of Axios in Vue.js along with examples and code implementation. You may also have a look at the following articles to learn more –