Next.js开发Twitter克隆遇fetch请求及序列化报错求助
Next.js Twitter克隆项目fetch接口异常排查
问题背景
- 跟随教程使用Next.js + TailwindCSS + TypeScript技术栈开发Twitter克隆项目,完全对照教程步骤编写代码,疑似IDE或Next.js版本差异导致运行报错,当前教程进度1:42:05 / 3:17:52
初始报错
最初编写的fetchTweets函数代码如下:
import { Tweet } from "../typings" export const fetchTweets = async () => { const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`) const data = await res.json(); const tweets: Tweet[] = data.tweets; return tweets }
运行后触发SSL协议错误:
FetchError: request to https://localhost:3000/api/getTweets/ failed, reason: write EPROTO 140020696905664:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332
错误触发时机为页面生成阶段,相关日志输出在运行终端窗口。
二次修改后报错
尝试新增global.window环境判断,修改后代码如下:
import { Tweet } from "../typings" export const fetchTweets = async () => { if(global.window) { const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`) const data = await res.json(); const tweets: Tweet[] = data.tweets; return tweets } }
修改后触发服务端序列化错误:
Error: Error serializing
.tweetsreturned fromgetServerSidePropsin "/". Reason:undefinedcannot be serialized as JSON. Please usenullor omit this value
根因分析
- 第一次SSL报错:本地Next.js开发服务默认以HTTP协议启动,环境变量
NEXT_PUBLIC_BASE_URL配置为https://localhost:3000,协议不匹配导致SSL握手失败 - 第二次序列化报错:
getServerSideProps运行在服务端环境,服务端不存在window对象,判断逻辑直接跳过fetch执行流程,函数默认返回undefined,Next.js不支持序列化undefined值作为页面props
修复方案
- 修正环境变量配置
打开项目根目录.env.local文件,将NEXT_PUBLIC_BASE_URL调整为本地开发对应HTTP地址:NEXT_PUBLIC_BASE_URL=http://localhost:3000,生产部署时再替换为实际线上HTTPS域名。 - 调整
fetchTweets函数逻辑,移除无效的window判断,增加异常兜底:
import { Tweet } from "../typings" export const fetchTweets = async () => { // 兼容服务端/客户端请求地址 const baseUrl = typeof window === 'undefined' ? process.env.NEXT_PUBLIC_BASE_URL?.replace('https://', 'http://') || 'http://localhost:3000' : process.env.NEXT_PUBLIC_BASE_URL || '' const res = await fetch(`${baseUrl}/api/getTweets`) if (!res.ok) return [] const data = await res.json(); return (data.tweets ?? []) as Tweet[]; }
getServerSideProps增加返回值兜底,彻底避免undefined序列化问题:
export const getServerSideProps = async () => { const tweets = await fetchTweets() return { props: { tweets: Array.isArray(tweets) ? tweets : [] } } }
修改完成后重启Next.js开发服务即可正常运行。
内容的提问来源于stack exchange,提问作者SashaBRRRR
相关产品推荐
相关产品推荐

