Axios is a promised-based HTTP client for Node.js apps. We worked with vanilla promises with the asyncData method in the previous section. We can simplify our code further and save some lines with Axios, which is powered by asynchronous JavaScript and XML (AJAX) to make asynchronous HTTP requests. Let's get it started in the following steps:
- Install Axios via npm:
$ npm i axios
We should always use a full path when making HTTP requests with Axios:
axios.get('https://jsonplaceholder.typicode.com/posts')
But it can be repetitive to include https://jsonplaceholder.typicode.com/ in the path for every request. Besides, this base URL can change over time. So we should abstract it and simplify the request:
axios.get('/posts')
- Create an Axios instance in the /plugins/ directory:
// plugins/axios-api.js
import axios from 'axios'
export default axios.create({
baseURL: 'http://localhost:3000'
})
- Import this...