In this spa-mode exercise, we will need two Axios instances to make API calls to the following addresses:
- localhost:4000 for user authentication
- jsonplaceholder.typicode.com for fetching users
We will use the vanilla Axios (https://github.com/axios/axios) as it gives us the flexibility to create multiple instances of Axios with some custom configurations. Let's get started:
- Install the vanilla axios via npm:
$ npm i axios
- Create an axios instance on the page you need it:
// pages/users/index.vue
const instance = axios.create({
baseURL: '<api-address>',
timeout: <value>,
headers: { '<x-custom-header>': '<value>' }
})
But creating the axios instance directly on a page is not ideal. Ideally, we should be able to extract this instance and reuse it anywhere. Through the Nuxt plugin, we can create the Axios extracted instance. There are two methods we can follow to create...