Guide on integrating the @nuxtjs/axios plugin with Nuxt3

I'm trying to fetch API data from using this code:

<template>
<div>


</div>
</template>


  <script>  
  definePageMeta({
    layout: "products"
  })

export default {
  data () {
    return {
      data: '',
    }
  },
  async fetch() {
    const res = await this.$axios.get('https://fakestoreapi.com/products/')
    console.log(res.data)
  },
}
</script>

I have axios installed and in my nuxt.config.ts file, I added:

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({

    app: {
        head: {
            title: 'Nuxt',
            meta: [
                { name: 'description', content: 'Everything about - Nuxt-3'}
            ],
            link: [
                {rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons' }
            ]
        }
    },
    runtimeConfig: {
        currencyKey: process.env.CURRENCY_API_KEY
    },
    modules: [
       "@nuxtjs/tailwindcss",
    ],
    buildModules: [
        "@nuxtjs/axios"
    ],
    axios: {
      baseURL: '/',
    }
})

When I check my console, I see the following message:

is an experimental feature and its API will likely change.

However, I am not seeing any API data being logged in the console. What could be the issue?

Answer №1

According to the information provided here, the @nuxtjs/axios module is no longer used with Nuxt3. Instead, it has been replaced by ohmyfetch, which is now integrated directly into the framework's core as $axios as explained here.

Therefore, your configuration file should be structured like this:

export default defineNuxtConfig({
  app: {
    head: {
      title: 'Nuxt Dojo',
      meta: [
        { name: 'description', content: 'Everything about - Nuxt-3' }
      ],
      link: [
        { rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons' }
      ]
    }
  },
  runtimeConfig: {
    currencyKey: process.env.CURRENCY_API_KEY
  },
  modules: [
    "@nuxtjs/tailwindcss"
  ],
})

The code for the /pages/products/index.vue page can be structured as follows:

<template>
  <div>
    <p v-for="user in users" :key="user.id">ID: {{ user.id }} 👉 {{ user.name }}</p>
  </div>
</template>

<script>
definePageMeta({ layout: "products" })

export default {
  data () {
    return {
      users: '',
    }
  },
  async mounted() {
    this.users = await $fetch('https://jsonplaceholder.typicode.com/users')
  },
}
</script>

The end result will look something like this (with a successful HTTP request shown in the network tab):


It is confirmed that the module is not supported (and will not be) in Nuxt3, as stated on the modules page.

More information on the Suspense error can be found in the official documentation:

<Suspense> is an experimental feature. It is subject to change before reaching stable status.

Although it may sound intimidating, you can still utilize the API without any issues since it is just a warning and not an error!

Answer №2

When working with nuxtjs3, I find it beneficial to utilize a composable as it offers flexibility and can be easily imported throughout the application.

composables/useApi.ts

import axios from 'axios'

export const useApi = () => {
  const baseURL = 'https://BASE_URL.com'
  const storeUser = useStoreUser()

  return axios.create({
    baseURL,
    headers: {
      Authorization: `Bearer ${storeUser.token}`
    }
  })
}

The process now involves:

<script lang="ts" setup>
const api = useApi()

const { data } = await api({
    method: 'get',
    url: '/auth/login'
})
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring data from AJAX to PHP

I am currently developing a project in PHP. I have created an associative array that functions as a dictionary. Additionally, I have a string containing text with placeholders for keys from the array. My goal is to generate a new String where these key wor ...

Storing chosen choices from various select lists with similar class name in JavaScript

I am struggling to save all the selected options in an array for future output. Despite trying various suggestions, I haven't been able to make it work yet. The class names and names cannot be modified. HTML <select class="addon addon-select" nam ...

NodeJS is facing a severe challenge in properly rendering HTML and its accompanying CSS code, causing a major

Once upon a time, I built a beautiful website while practicing HTML, CSS, and JS. It had multiple web pages and used Express for the backend. Unfortunately, I lost all the files associated with it and took a break from web programming for some time. Now, w ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

Calculating and displaying the output on an HTML page: A step-by-step guide

Within my HTML, I have two values stored in Session Storage: "Money" and "Time". These values are based on what the user inputted on a previous page. For example, if someone entered that they need to pay $100 in 2 days. My goal is to generate a list that ...

What is the best way to hide or eliminate spinners/arrows in react-select?

I am currently utilizing react-select for my project, but I'm encountering an issue with removing the spinners/arrows from the dropdown menu. So far, I have successfully removed the default separator "|" and Dropdown Indicator using the following cod ...

The background color of absolute divs fails to extend across the entire screen

Trying to implement a loading screen in my VueJs app using only divs. The issue is that the background color of the divs (loadingScreen) does not cover the entire screen, but only as much as the loader's height. I've attempted adding margin to th ...

In order to preserve the data inputted by the user within a file

Check out this HTML code snippet:- ` AngularJS | $http server <div ng-controller="people"> <ul> <h2> Names and Ages of programmers: </h2> <li ng-repeat="person in persons"> { ...

Guide to integrating a menu in Vue.js

I am currently facing an issue with importing a component from vue.js into my App.vue file. Here is the code for the component: <template> <h1> Hello</h1> </template> <script> export default { } </script> And here ...

What is the best way to retain selection while clicking on another item using jQuery?

There is a specific issue I am facing with text selection on the page. When I apply this code snippet, the selected text does not get de-selected even after clicking .container: jQuery('.container').on("mousedown", function(){ jQuery('. ...

Uniting the client-side jQuery and server-side Express for enhanced functionality

Currently, I am deepening my understanding of Express/Node. My goal is to construct a basic HTML form that undergoes client-side validation (using jQuery/AJAX) while also being processed server-side (via Express.js). The application's complexity remai ...

Verify the accuracy of quiz responses with PHP and AJAX

I am working on a picture quiz that has one input field for each image. I am looking for a solution to verify if the value entered into the input field matches the correct answer. If it does match, I need to perform certain operations like adding or removi ...

Guide for sending token through Authorization in Laravel 8 API

I am currently utilizing Laravel 8 as an API REST and encountering an issue where my token is null when sent in the AJAX request. I have successfully handled logins and requests without tokens, but this specific scenario has me puzzled. Within my JavaScri ...

problem with passing the identification number into the function

I am facing an issue with passing the id into a javascript onClick method. I am using the Spring framework and in the controller class, I send the related id to the JSP file like this: model.addAttribute("uploadid", uploadid); Afterwards, I need to p ...

How can you show the default calendar for a specific month and year in a Vue3 datepicker?

I've been utilizing the @vuepic/vue3datepicker component, which automatically shows the days of the current month when integrated in my project: <template> <VueDatePicker v-model="date" inline></VueDatePicker> </templ ...

Within the materia-ui table, I am facing an issue where clicking the button to expand a row results in all rows expanding. I am seeking a solution to ensure only the selected row expands

When a row is clicked, all rows in the data table expand to show inner data for each row. The issue is that clicking the expand button expands all rows rather than just the selected row. Each time I try to expand one specific row, it ends up expanding mul ...

Using vue-router within a pinia store: a step-by-step guide

I'm currently setting up an authentication store using Firebase, and I want to direct users to the login/logged page based on their authentication status. My goal is similar to this implementation: https://github.com/dannyconnell/vue-composition-api- ...

Tips for effectively managing dynamic xpaths

When conducting a search operation, I am required to select the text that is returned as a result. Each search will produce different xpaths. Below are examples of various xpaths returned during a search: .//*[@id='messageBoxForm']/div/div[1]/di ...

cracking reCAPTCHA without needing to click a button or submit a form (utilizing callback functions)

Currently, I am facing a challenge with solving a reCaptcha on a specific website that I am trying to extract data from. Typically, the process involves locating the captcha inside a form, sending the captcha data to a captcha-solving API (I'm using ...

The call stack in mongodb has surpassed its maximum size limit

I am currently executing a method. Method execution var message = "Hello" function1("78945612387", message, null, "Portalsms") Node JS Code function function1(mobileno,body,logExtraInfo,messageType){ request(uri, function (error, resp ...