You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt3中使用@nuxtjs/axios模块?API请求无数据问题排查

问题解决

问题原因

你使用的@nuxtjs/axios是为Nuxt2设计的适配模块,在Nuxt3环境下属于实验性特性,因此会出现API可能变更的提示,同时存在兼容性问题导致无法正常获取数据。

解决方案(推荐使用Nuxt3内置工具)

1. 修改页面代码(改用useFetch)

替换原页面的<script>部分,使用Nuxt3官方内置的useFetch方法获取数据:

<template>
  <div>
    <!-- 可选:渲染获取到的数据示例 -->
    <div v-for="product in products" :key="product.id">
      <h4>{{ product.title }}</h4>
    </div>
  </div>
</template>

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

// 直接通过useFetch获取API数据,data会自动成为响应式变量
const { data: products } = await useFetch('https://fakestoreapi.com/products/')
// 在控制台查看数据(注意要访问.value,因为是响应式对象)
console.log(products.value)
</script>

2. 清理Nuxt配置文件

打开nuxt.config.ts,移除所有和@nuxtjs/axios相关的配置项,修改后内容如下:

// 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",
    ]
})

备选方案(坚持使用axios)

如果你一定要用axios,可通过自定义插件的方式引入普通axios包:

1. 安装普通axios

npm install axios

2. 创建axios插件

在项目根目录创建plugins/axios.ts文件,内容如下:

import axios from 'axios'

export default defineNuxtPlugin(() => {
  const axiosInstance = axios.create({
    baseURL: '/'
  })
  return {
    provide: {
      axios: axiosInstance
    }
  }
})

3. 修改页面代码

<template>
  <div></div>
</template>

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

// 获取Nuxt应用实例中的axios
const { $axios } = useNuxtApp()

async function fetchProducts() {
  const res = await $axios.get('https://fakestoreapi.com/products/')
  console.log(res.data)
}

// 调用数据获取方法
await fetchProducts()
</script>

4. 清理Nuxt配置

同样需要移除nuxt.config.ts中buildModules和axios相关的配置项。

内容的提问来源于stack exchange,提问作者Azizxon Zufarov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:31:15