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

Next.js通过Axios获取Strapi数据失败,求正确实现方案

Next.js + Strapi Axios GET请求数据报错解决方案

我正在使用Next.js与Strapi框架开发,参照旧教程视频实现Axios GET请求从Strapi获取数据,但运行未达预期并报错。报错位置为页面组件中访问pages[0].Title与pages[0].Description处。

原代码

import axios from "axios";
import Head from "next/head";
import * as React from "react";
import * as Material from "@mui/material";
import IconButton from '@mui/material/IconButton';
import Badge from '@mui/material/Badge';
import MailIcon from '@mui/icons-material/Mail';
import styles from "../styles/Home.module.css";
import { Container } from "@mui/material";

function notificationsLabel(count) {
  if (count === 0) {
    return 'no notifications';
  }
  if (count > 99) {
    return 'more than 99 notifications';
  }
  return `${count} notifications`;
}

export default function Home({ pages }) {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <h1>{pages[0].Title}</h1>
      <h2>{pages[0].Description}</h2>
    </div>
  );
}

export async function getServerSideProps() {
  const postRes = await axios.get("http://localhost:1337/api/pages");
  return {
    props: {
      pages: postRes.data
    },
  };
}

错误信息

es\react-dom\cjs\react-dom-server.browser.development.js:6076:14)
page: '/'
36 |           <h1>{pages[0].Title}</h1>
|                        ^
37 |           <h2>{pages[0].Description}</h2>

问题核心

旧教程大概率基于Strapi v3,而当前使用的Strapi v4 API响应结构已变更:

  • Strapi v3直接返回数据数组,v4则将数据包裹在data.data中,且每个条目字段存放在attributes对象内
  • 直接访问pages[0]会因pages不是预期的数组而报错,或pages[0]为undefined

正确实现流程

1. 确认Strapi API响应结构

先在浏览器访问http://localhost:1337/api/pages,查看返回的JSON格式,Strapi v4典型响应如下:

{
  "data": [
    {
      "id": 1,
      "attributes": {
        "title": "首页标题",
        "description": "首页描述",
        "createdAt": "2024-05-20T12:00:00.000Z"
      }
    }
  ],
  "meta": {
    "pagination": {
      "page": 1,
      "pageSize": 25,
      "pageCount": 1,
      "total": 1
    }
  }
}

2. 修改数据获取逻辑(getServerSideProps)

调整代码以适配Strapi v4的响应结构,同时增加错误处理:

export async function getServerSideProps() {
  try {
    const postRes = await axios.get("http://localhost:1337/api/pages");
    // 提取实际数据并扁平化attributes字段
    const pages = postRes.data.data.map(item => ({
      id: item.id,
      ...item.attributes
    }));
    return {
      props: {
        pages
      },
    };
  } catch (error) {
    console.error("获取页面数据失败:", error);
    // 出错时返回空数组避免组件报错
    return {
      props: {
        pages: []
      }
    };
  }
}

3. 修改页面组件,处理空数据场景

避免直接访问pages[0]导致的报错,增加空数据判断:

export default function Home({ pages }) {
  // 无数据时显示提示
  if (pages.length === 0) {
    return (
      <div className={styles.container}>
        <Head>
          <title>Create Next App</title>
          <link rel="icon" href="/favicon.ico" />
        </Head>
        <p>暂无页面数据</p>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      {/* 注意字段名要和Strapi后台配置一致,默认是小写驼峰 */}
      <h1>{pages[0].title}</h1>
      <h2>{pages[0].description}</h2>
    </div>
  );
}

4. 额外配置检查

  • 确保Strapi后台的pages内容类型已有已发布的条目
  • 若Strapi开启了权限控制,需在「设置-角色与权限-公共角色」中,给pages的find权限勾选允许

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:18:38