Next.js中getServerSideProps数据获取异常,页面加载停滞求助
Next.js页面数据获取后持续加载无法显示问题解决
问题描述
我正在学习Next.js,开发一个包含用户录入表单和用户列表展示的单页网站。用户录入功能已通过API调用实现,但数据获取环节出问题:原本打算用getServerSideProps,但代码里实际写的是getStaticProps,终端能打印出数据,但页面一直处于加载状态无法正常显示。
页面代码(原代码)
import Head from 'next/head' import Image from 'next/image' import styles from '../styles/Home.module.css' export default function Home({utenti}) { return ( <> <form method="POST" action='/api/sendInfo'> <label>Nome</label> <input type="text" name="nome"></input> <label>Cognome</label> <input type="text" name="cognome"></input> <label>Email</label> <input type="email" name="email"></input> <button type="submit">Invia</button> </form> <div> <p>Select Utenti</p> <button type="submit" action = '/api/getInfo' method="GET"> prendi utenti</button> </div> </> ) } export async function getStaticProps () { // Fetch data from external API const res = await fetch('http:127.0.0.1:3000/api/getInfo') const data = res.json() console.log ("Questi sono i data"); console.log (data); // res.json(data) // Pass data to the page via props return { utenti: { utenti: data } } }
API接口代码(原代码)
import connection from "../../db"; export default async(req, res) => { try{ const query = 'SELECT * FROM Utenti' const result = await connection.query( query, ); console.log(result); }catch(err){ console.log(err); } res.redirect("/"); }
问题根源及修复方案
1. API接口未返回有效数据,反而重定向
你的/api/getInfo接口执行数据库查询后,没有将结果以JSON形式返回给请求方,而是直接调用res.redirect("/"),导致getStaticProps中的fetch请求拿到的是重定向响应,无法解析出用户数据,页面自然无法正常渲染。
修复后的API代码:
import connection from "../../db"; export default async(req, res) => { try { const query = 'SELECT * FROM Utenti'; const result = await connection.query(query); console.log(result); // 将查询结果以JSON格式返回 res.status(200).json({ utenti: result }); } catch(err) { console.log(err); // 错误时返回500状态码和错误信息 res.status(500).json({ error: err.message }); } // 移除重定向代码 }
2. getStaticProps的两处错误
- 缺少
await解析JSON:res.json()是异步操作,必须加await才能拿到实际数据,否则data是一个未解析的Promise对象。 - 返回格式错误:
getStaticProps要求返回包含props字段的对象,你直接返回{utenti: ...},Next.js无法识别并传递给页面组件。
修复后的getStaticProps:
export async function getStaticProps () { // 补全URL的http://前缀 const res = await fetch('http://127.0.0.1:3000/api/getInfo'); // 必须用await解析JSON响应 const data = await res.json(); console.log("Questi sono i data"); console.log(data); // 正确返回props结构 return { props: { utenti: data.utenti } } }
3. 页面组件未渲染用户列表
你已经在组件中接收了utenti props,但没有添加渲染逻辑,导致数据拿到后无法展示。同时按钮的用法错误:button标签不支持action和method属性,这些是form标签的专属属性。
修复后的页面组件:
import Head from 'next/head' import Image from 'next/image' import styles from '../styles/Home.module.css' export default function Home({utenti}) { return ( <> <form method="POST" action='/api/sendInfo'> <label>Nome</label> <input type="text" name="nome"></input> <label>Cognome</label> <input type="text" name="cognome"></input> <label>Email</label> <input type="email" name="email"></input> <button type="submit">Invia</button> </form> <div> <p>Select Utenti</p> {/* 直接渲染getStaticProps预获取的用户数据 */} <div className={styles.userList}> <h3>用户列表</h3> {utenti ? ( <ul> {utenti.map((user, index) => ( <li key={index}> {user.nome} {user.cognome} - {user.email} </li> ))} </ul> ) : ( <p>暂无用户数据</p> )} </div> </div> </> ) }
4. 关于getServerSideProps的补充
如果你需要每次请求都获取最新数据(而不是构建时静态生成),可以把getStaticProps换成getServerSideProps,用法和修复后的getStaticProps几乎一致,只需要修改函数名即可:
export async function getServerSideProps () { const res = await fetch('http://127.0.0.1:3000/api/getInfo'); const data = await res.json(); return { props: { utenti: data.utenti } } }
内容的提问来源于stack exchange,提问作者DiegoM
相关产品推荐
相关产品推荐

