Another method of creating the custom Axios instance does not involve the Nuxt config at all. We can just export the custom instance as a regular JavaScript function and then import it directly into the page where we need it. Let's take a look at how to do this:
- Create an axios-api.js file in the /plugins/ directory, import the vanilla axios, and create the instance, as follows:
// plugins/axios-api.js
import axios from 'axios'
export default axios.create({
baseURL: 'http://localhost:4000',
withCredentials: true
})
As you can see, we're no longer using the inject method; instead, we export the instance directly.
- Now, we can import it manually when we need it. In this example, we need it in the login action method, as follows:
// store/actions.js
import axios from '~/plugins/axios-api'
async login({ commit }, { username, password }) {
const { data } = await axios.post('/public/users/login', ...