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):

https://i.sstatic.net/11pPf.png


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

What is the best way to exclude a specific key when adding JSON objects to an array?

I'm facing a challenge with a JSON array of objects that contains other arrays of objects. The structure of this array is not fixed, making it difficult for me to delete specific elements like delete mainArray[0].obj.subobj[1].objToOmit; In my progra ...

Navigating Dynamically between tabs - A How-to Guide

I am working on a mat-tab Angular app where I need to dynamically generate links and transfer them to a navLinks object. Despite ensuring that the concatenation is correct, it seems like my approach is not working as expected. Here's a glimpse of what ...

Storing a token in NodeJS using JavaScript

We currently have a mobile single-page application built using HTML/CSS/NodeJS. The functionality of this app requires numerous API calls, all of which require a bearer token for authorization purposes. This bearer token is simply a string value that we ge ...

After running javascript, Elements do not retain any values

I have encountered an issue with two button click events - one is in Javascript and the other in VB. The first button (Javascript) retrieves values from various controls like textboxes and dropdown lists, while the second button (VB) saves these values to ...

Efficient communication in Angular: Sharing data among controllers and components

Recently joining a new project, I am faced with the task of implementing a small feature. In my setup, there are 2 distinct views: Cars.html and Wheels.html The Cars.html view is associated with the controller Cars.controller.js On the other hand, the W ...

Understanding the moment when the DOM is fully rendered within a controller

I'm currently facing an issue with AngularJS. In my controller, I have a $watch setup like this: function MyController() { $watch('myModel', function() { $rootScope.$emit('do-oper'); }); } The value of 'myMod ...

Having trouble setting up react-i18n with hooks and encountering a TypeError: Cannot read property '0' of undefined?

Encountering an error while setting up the react-i18n with hooks: TypeError: Cannot read property '0' of undefined Here's the content of i18n.js: import i18n from 'i18next'; import { initReactI18next } from 'react-i18next/h ...

Is it possible for .getElementByClassName to identify Ajax.GET elements?

I've run into a problem that I need help with: The issue arises when I have an API that makes an Ajax GET request. In the success function, it creates a button, a div, and several span elements with information inside, each with its own class. The GE ...

Error message: ReactJs encountered a TypeError stating that categories.map is not a function

Encountered the following issue: Error: TypeError: categories.map is not a function Snippet from App.js: export default function Header() { const [categories, setCategories] = useState([]); useEffect(() => { const loadCategor ...

A comparison between Buffer.byteLength and file size

I'm facing an issue with file size discrepancies. I have a file that is reported as 51Mb in Finder, but when uploaded to the server, the byteLength of the Buffer shows a much smaller size. Could this difference be due to the file type or other propert ...

Prevent the browser back button from being used in a web application that requires CLIENT_CERT authentication

My website utilizes CLIENT_CERT JAAS authentication and is compatible with IE7. After logging out, when I return to the home page and click on the back button, I want to stay on the same non-secure page. I have been able to achieve this using the history. ...

Display the HTML element prior to initiating the synchronous AJAX request

I'm looking to display a <div> upon clicking submit before triggering $.ajax() Here's my HTML: <div id="waiting_div"></div> This is the CSS: #waiting_div { position: fixed; top: 0px; left: 0px; height: 100%; ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...

The db.all method does not provide an array as its return variable

Seeking to extract an array from the db.all function to incorporate it into a custom JSON object for a response. Various attempts have been made including using Object.values(members), members.fulfillmentValue, and some PROMISE methods discovered on Stack ...

What is the reason behind the blocking of Ajax GET requests without CORS, while JSONP requests are permitted?

Accessing any page on the web through a GET request using HTML tags from a different origin is possible: <script src="http://example.com/user/post?txt=sample"></script> XHR requests to other origins are blocked for security reasons. For examp ...

Implementing complex routing with Express.js on top of Node.js

Recently delving into the world of javascript, I have embarked on creating a RESTful API using Node.js and Express.js Here is the breakdown of my directory structure: /server.js /api/api.js /api/location/location.js My goal is to make the API modular, ...

Using Angular NgRx - triggering an action from an effect once certain actions yield a result

I'm encountering difficulties in dispatching actions that require results from five other actions (all listed in my effect). Could someone lend a hand? Essentially, I need to trigger an action within the effect only after these five actions have retu ...

Issues encountered with NodeJS servers experiencing unresponsive posts

I am currently conducting API tests on my NodeJS server, which is hosted on a domain (server.domainname.com), while sending requests from my local development environment (i.e. localhost:3000). The issue I'm encountering is that when I make an Axios P ...

What are the best practices for implementing serialization in NestJS?

Recently, I delved into a fresh NestJs project and encountered a hurdle while trying to integrate serialization. The goal was to transform objects before sending them in a network response. Initially, everything seemed to be working smoothly until I attemp ...

Comparison of getComputedStyle() and cssText functionality between Internet Explorer and Firefox

Take a look at this example to see the issue in action. I'm attempting to access the cssText property of a <div> using window.getComputedStyle(element) (which provides a CSSStyleDeclaration object). While this works smoothly in Chrome, it' ...