Next.js中getServerSideProps内调用axios接口始终报错如何解决?
错误根因
Next.js 要求
getServerSideProps只能返回包含props/notFound/redirect三个可选字段的标准对象,不允许直接返回 Error 实例。你当前代码的 catch 分支直接返回了 Axios 抛出的错误对象,这个对象本身携带了config/request/response等额外字段,不符合 Next.js 的返回规则,因此触发报错。
修复方案
在 catch 分支返回符合 Next.js 要求的结构即可,根据你的业务需求可以选择以下两种常用处理方式:
方式1:请求出错时返回404页
export const getServerSideProps: GetServerSideProps = async (ctx) => { try { const { userId, token } = ctx.req.cookies; const res = await api.get(`/users/show/${userId}`, { headers: { token }, }) const userData = res.data; if (!userData) { return { notFound: true, } } return { props: { userData } } } catch (error) { // 出错时返回404,也可根据业务逻辑调整为其他返回规则 return { notFound: true } } }
方式2:把错误信息传给页面组件自行处理
export const getServerSideProps: GetServerSideProps = async (ctx) => { try { const { userId, token } = ctx.req.cookies; const res = await api.get(`/users/show/${userId}`, { headers: { token }, }) const userData = res.data; if (!userData) { return { notFound: true, } } return { props: { userData, error: null } } } catch (error) { return { props: { userData: null, // 只取需要的错误信息,不要返回整个Axios错误对象 error: error?.response?.data?.msg || '请求用户信息失败' } } } }
额外注意事项
如果请求错误是因为token过期/无效,推荐在catch分支返回redirect配置跳转到登录页,示例:
return { redirect: { destination: '/login', permanent: false } }
不要直接把整个Axios错误对象放到props里,避免泄露服务端请求的敏感信息(比如接口地址、请求头配置等)
内容的提问来源于stack exchange,提问作者Djony
相关产品推荐
相关产品推荐

