This Vue 2 tutorial explains making the AJAX Requests in Vue Js applications using Axios and fetch API.
What Is AJAX?
AJAX is an asynchronous Javascript and XML widely used to access the webserver from the client-side over HTTP and HTTPS protocols.
AJAX supports XMLHttpRequest (XHR) objects. We can use API to render the data from a remote server and update the specific part of a web page that doesn’t refresh the entire web page.
Advantages Of AJAX
- Quicker Response Time
- Fast And User friendly
- Self-governing Server Technology
- Communicates Over HTTP Protocol
- Supports Client-Side Template Rendering
- Update A Specific Component Of A Web Page
How Does AJAX Work?
Let’s see how AJAX works:
- The user makes a request via API from eh client-side that directly goes to the XMLHttpRequest object.
- HTTP Request is sent to the server by XMLHttpRequest object transfers the HTTP request to the webserver.
- The remote server communicates with the database using the preferred programming language.
- Data is fetched from the server.
- The server sends data in the form of XML or JSON to XMLHttpRequest.
- Shows data on the browser that is retrieved from the server using HTML and CSS.
Basic AJAX Request Example In Javascript
Below is the basic AJAX request example coded in Javascript for the GET method:
// Make the HTTP request
var xhr = new XMLHttpRequest();
xhr.open('GET', 'manage-data.php');
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4;
var OK = 200;
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
console.log(xhr.responseText); // 'Result'
} else {
console.log('Error: ' + xhr.status); // Request error.
}
}
};
// Send request
xhr.send(null);
Getting Started With Vue App
To install the Vue project, we will install the latest Vue CLI 4 on our development system:
npm install -g @vue/cli
Start installing a new Vue project:
vue create vue-ajax-requests
Get inside the Vue project:
cd vue-ajax-requests
Error: digital envelope routines::unsupported
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'
To remove the above error for invoking the app, we have to make sure to update the “scripts”: [] array in the package.json file:
"scripts": {
"serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
"build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
"lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},
Vue Multi-word Error
To remove the multi-word error, we will add the following code in the vue.config.js file:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false,
})
Now, we will start the app in the browser:
npm run serve
Create Vue Component
Further, we have to create the ShowUsers.vue file inside the components folder:
<template>
<div>Vue Axios Http Client Example<div/>
</template>
<script>
export default {
data() {
return {};
};
}
</script>
Then, we import the Vue component inside the Javascript script tag, define the component name inside the components:{} object, and then define the component’s name within the template tag:
// App.vue
<template>
<div id="app">
<ShowUsers></ShowUsers>
</div>
</template>
<script>
import ShowUsers from './components/ShowUsers.vue'
export default {
name: 'App',
components: {
ShowUsers
}
}
</script>
Install Axios In Vue
Axios is an extremely popular JavaScript library for making HTTP requests. It is a Promise-based HTTP client for the browser and node.js. It works smoothly on the client and the server:
- Cancels requests
- Supports the Promise API
- Intercepts request and response
- Makes HTTP requests from node.js
- Automatic transforms for JSON data
- Transforms request and response data
- Makes XMLHttpRequests from the browser
- Client-side support for protecting against XSRF
We will use the given commands to install the Axios package in Vue:
# NPM
npm install axios --save
# Yarn
yarn add axios
Now, let’s see how to use Axios in the Vue component:
<script>
import axios from "axios";
export default {
data() {
return {};
}
};
</script>
We are going to use the following API from JSONPlaceHolder. JSONPlaceHolder is a simple fake REST API for testing and prototyping. It’s like an image placeholder but for web developers.
https://jsonplaceholder.typicode.com/users
We also need to define the mounted lifecycle hook in Vue to make the API calls:
<script>
import axios from "axios";
export default {
data() {
return {};
},
mounted() {
axios.get("https://jsonplaceholder.typicode.com/users")
}
};
</script>
Get And Display Data Using Axios In Vue.js
In this step, we will make the AJAX Request using the AXIOS and show how to get a response from the server and handle it via Promise Object.
A Promise Object in JavaScript provides surety for a probable result in the future. A Promise has three presumable states: fulfilled, rejected, and pending.
<template>
<div>
<ul class="test-list" v-for="user in usersList" :key="user.id">
<li class="test-list--item">
<strong>{{ user.name }}</strong> <br>
{{ user.email }} <br>
{{ user.website }}
</li>
</ul>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
usersList: []
};
},
mounted() {
axios.get("https://jsonplaceholder.typicode.com/users")
.then(res => {
this.usersList = res.data;
console.log(this.usersList)
})
.catch(error => {
console.log(error)
// Manage errors if found any
})
}
};
</script>
<style>
ul {
margin: 0 auto;
width: 300px;
text-align: left;
}
li {
display: block;
margin-bottom: 10px;
border: 1px solid #ccc;
padding: 15px;
}
</style>
The axios.get() method makes the API call and gets the response from the server. If the response is successful, then it goes to then block and if it fails, then it goes to the catch block.
Make AJAX Request In Vue.js With Fetch API
The Fetch API is a modernized substitute for XMLHttpRequest. Most of the libraries created consider XMLHttpRequest.
The Fetch API offers an uncomplicated interface for retrieving the resources. e can quickly render the data from the server and it supports Cross-Origin Resources Sharing (CORS).
How To Make Request With Fetch?
Let’s now see a basic example of fetching a JSON file using Fetch API:
fetch('https://api-url.json')
.then(function(response) {
// Response comes here
})
.catch(function(error) {
console.log('Found error: \n', error);
});
Afterward, we pass the API URL in the fetch() method to get the response from the web server. We can handle the server response in the then and catch block.
Below is the final code for displaying the data, and making fetch requests:
// vue-template.vue
<template>
<div>
<ul class="test-list" v-for="user in usersList" :key="user.id">
<li class="test-list--item">
<strong>{{ user.name }}</strong> <br>
{{ user.email }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
usersList: []
};
},
mounted() {
fetch("https://jsonplaceholder.typicode.com/users").then((res) => {
return res.json();
}).then((users) => {
this.usersList.push(...users);
}).catch(error => {
console.log(error)
})
}
};
</script>
<style>
ul {
margin: 0 auto;
width: 300px;
text-align: left;
}
li {
display: block;
margin-bottom: 10px;
border: 1px solid #ccc;
padding: 15px;
}
</style>
Conclusion
In this Vue 2 tutorial, we have seen how to send AJAX requests from the Vue.js application. We learned how to make REST API calls to the server to get the data.
Thanks