NextJS+Strapi博客评论功能报错:解构失败与404请求错误
问题修复方案
错误1:TypeError: Cannot destructure property 'blog' of 'param' as it is undefined.
原因
带"use client"标记的Next.js 13客户端组件不能定义为async函数,这种写法会破坏组件的props传递逻辑,导致blog参数无法正常接收。
修复
移除组件函数的async关键字,将API请求逻辑移到提交按钮的点击事件处理函数中。
错误2:AxiosError: Request failed with status code 404
原因
- Strapi关联数据格式错误:创建评论时关联博客的写法不符合Strapi REST API规范;
- 输入框状态绑定错误:
onChange事件中错误使用e.target.name而非e.target.value,导致输入内容无法存入state; - 组件初始化时就触发请求:当前代码在组件加载时直接发送POST请求,既无意义也会导致无效请求。
修复
- 修正输入框的状态绑定逻辑,改用
e.target.value更新state; - 包裹表单元素,通过
onSubmit事件触发提交逻辑; - 使用Strapi要求的关联数据格式
blog: { connect: [blog.id] }; - 为请求添加try/catch捕获异常,方便调试。
修正后的评论组件代码
"use client" import { useState } from "react"; import { api } from "../../http"; const SubmitComment = ({ blog }: any) => { const [name, setName] = useState<string>('') const [email, setEmail] = useState<string>('') const [comment, setComment] = useState<string>('') const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { const res = await api.post('/api/comments', { data: { name, email_id: email, comment, blog: { connect: [blog.id] } } }) console.log("评论提交成功:", res) // 提交成功后清空表单 setName(''); setEmail(''); setComment(''); } catch (err) { console.error("评论提交失败:", err) } } return ( <form onSubmit={handleSubmit}> <div className="grid lg:grid-cols-2 grid-cols-1 gap-2"> <input type="text" name="name" className="ml-2 bg-gray-100 h-8 rounded-full px-2 text-lg" placeholder="Your name" value={name} onChange={(e) => setName(e.target.value)} /> <input type="email" name="email" className="mr-2 bg-gray-100 h-8 rounded-full px-2 text-lg" placeholder="Your Email ID" value={email} onChange={(e) => setEmail(e.target.value)} /> <textarea className="mx-2 lg:col-span-2 bg-gray-100 rounded-lg px-2 text-lg" placeholder="Comment" rows={5} value={comment} onChange={(e) => setComment(e.target.value)} ></textarea> </div> <div className="flex justify-center my-2"> <button type="submit" className="button"> Submit </button> </div> </form> ); }; export default SubmitComment;
额外注意事项
- 确保Strapi后台中,评论内容类型的
blog字段已设置为与博客的Belongs To关联关系; - 检查Strapi的权限设置:在
Settings > Roles > Public中开启评论的"创建"权限; - 博文页面可添加空值判断,避免
blog未加载时传递无效props:
{blog && <SubmitComment blog={blog} />}
内容的提问来源于stack exchange,提问作者user17680380
相关产品推荐
相关产品推荐

