Lesson 07-Nuxt.js API Integration

API Data Request Methods

Using asyncData

asyncData is a lifecycle hook provided by Nuxt.js that allows asynchronous data fetching during the initial page load.

// pages/index.vue
export default {
  async asyncData({ $axios }) {
    const response = await $axios.$get('/api/data');
    return {
      items: response.data,
    };
  },
};

Using fetch

The fetch method can be used to fetch data during page updates, making it suitable for dynamic content.

// pages/index.vue
export default {
  async fetch({ $axios, store }) {
    const response = await $axios.$get('/api/data');
    store.commit('setData', response.data);
  },
  computed: {
    items() {
      return this.$store.state.data;
    },
  },
};

Using Vuex

If you’re using Vuex for state management, you can place data request logic in Vuex actions.

// store/index.js
export default {
  state: {
    items: [],
  },
  mutations: {
    setData(state, data) {
      state.items = data;
    },
  },
  actions: {
    async fetchData({ commit }, $axios) {
      const response = await $axios.$get('/api/data');
      commit('setData', response.data);
    },
  },
};

// pages/index.vue
export default {
  async fetch({ store }) {
    await store.dispatch('fetchData');
  },
  computed: {
    items() {
      return this.$store.state.items;
    },
  },
};

Using Middleware

Middleware can be used to handle page-level data requests.

// middleware/auth.js
import axios from '~/plugins/axios';

export default function ({ store, redirect }) {
  axios
    .$get('/api/data')
    .then(response => {
      store.commit('setData', response.data);
    })
    .catch(error => {
      console.error(error);
      redirect('/');
    });
}

Using Axios Directly in Components

You can also use Axios directly within components for data requests.

// components/MyComponent.vue
<script>
import axios from '~/plugins/axios';

export default {
  data() {
    return {
      items: [],
    };
  },
  async mounted() {
    const response = await axios.get('/api/data');
    this.items = response.data;
  },
};
</script>

Using Nuxt.js Built-in Axios Plugin

Nuxt.js provides a built-in Axios plugin, @nuxtjs/axios, which simplifies configuration and offers useful default settings.

// nuxt.config.js
export default {
  modules: ['@nuxtjs/axios', '@nuxtjs/proxy'],
  axios: {
    proxy: true,
  },
  proxy: {
    '/api': {
      target: 'https://your-api-server.com/api',
      pathRewrite: {
        '^/api': '',
      },
    },
  },
};

Then, use $axios in pages or components:

// pages/index.vue
export default {
  async asyncData({ $axios }) {
    const response = await $axios.$get('/api/data');
    return {
      items: response.data,
    };
  },
};

Using Axios or Other Libraries for Data Requests

Installing Axios

Ensure Axios is installed. If not, install it with the following command:

npm install axios

Configuring Axios

To make Axios accessible throughout the application, create a file in the plugins folder to configure and export an Axios instance.

Create axios.js in the plugins folder:

// plugins/axios.js
import Vue from 'vue';
import axios from 'axios';

// Set base URL
axios.defaults.baseURL = 'https://api.example.com/';

// Add request interceptor
axios.interceptors.request.use(
  function (config) {
    // Do something before sending the request
    return config;
  },
  function (error) {
    // Handle request errors
    return Promise.reject(error);
  }
);

// Add response interceptor
axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    return response;
  },
  function (error) {
    // Handle response errors
    return Promise.reject(error);
  }
);

// Mount Axios to Vue prototype
Vue.prototype.$axios = axios;

Registering the Plugin

Register the plugin in the nuxt.config.js file:

// nuxt.config.js
export default {
  plugins: ['~/plugins/axios'],
};

Using Axios in Pages or Components

You can now use $axios to send HTTP requests in any page or component.

Sending a GET request with $axios in a page:

// pages/index.vue
export default {
  data() {
    return {
      items: [],
    };
  },
  async asyncData({ $axios }) {
    const response = await $axios.$get('/data');
    return { items: response.data };
  },
};

Or in a component:

// components/MyComponent.vue
export default {
  data() {
    return {
      items: [],
    };
  },
  async mounted() {
    const response = await this.$axios.get('/data');
    this.items = response.data;
  },
};

Handling Errors

You can also add error handling logic:

// pages/index.vue
export default {
  data() {
    return {
      items: [],
      error: null,
    };
  },
  async asyncData({ $axios, error }) {
    try {
      const response = await $axios.$get('/data');
      return { items: response.data };
    } catch (err) {
      error({ statusCode: err.response.status, message: err.response.statusText });
      this.error = err.message;
    }
  },
};

Using Other HTTP Clients

In addition to Axios, you can use other HTTP client libraries, such as the fetch API or unfetch.

Using unfetch

unfetch is a lightweight fetch polyfill suitable for use in Nuxt.js.

Install unfetch:

npm install unfetch

Create unfetch.js in the plugins folder:

// plugins/unfetch.js
import Vue from 'vue';
import unfetch from 'unfetch';

Vue.prototype.$fetch = unfetch;

Use $fetch in pages or components:

// pages/index.vue
export default {
  data() {
    return {
      items: [],
    };
  },
  async asyncData({ $fetch }) {
    const response = await $fetch('/data');
    const data = await response.json();
    return { items: data };
  },
};
Share your love