MERN栈评论功能问题:前端提交内容未存入数据库
评论功能前端提交无内容问题排查与修复
问题描述
在娱乐网站实现评论功能,后端经Postman测试可正常将评论内容存入数据库;但前端提交评论时,数据库无对应内容,后端控制台打印空请求体{}。
相关代码
前端评论表单逻辑
export default function AddComment({ busy}) { const [content, setContent] = useState(""); const { movieId } = useParams(); const { updateNotification } = useNotification(); const handleOnChange = ({ target }) => { setContent(target.value); }; const handleSubmit = async (e) => { e.preventDefault(); const { error, message } = await addComment(movieId); if (error) return updateNotification("error", error); updateNotification("success", message); const newComment = { content, }; setContent(newComment); setContent(""); }; return ( <div className='p-5'> <br /> <p className='dark:text-white text-primary'>replies</p> <hr className='w-64' /> {/* Comment Lists */} {/* Root Comment Form */} {/* Form */} <form className='flex ' onSubmit={handleSubmit} busy={busy}> <textarea value={content} onChange={handleOnChange} type='text' autoComplete='text' className='w-full rounded-md p-2 dark:text-white text-primary outline-none bg-transparent resize-none border-b focus:border-blue-500' placeholder='Add New comment' /> <br className='dark:text-white text-primary ' /> <button type='submit' className=' w-5 h-14 dark:text-white text-primary bg-blue-600 hover:bg-blue-400 focus:border-blue-900 rounded-md' > {busy ? <ImSpinner3 className='animate-spin' /> : "Add"} </button> </form> </div> ); }
API层addComment函数
import { catchError, getToken } from "../utils/helper"; import client from "./client"; export const addComment = async (movieId, newComment) => { const token = getToken(); try { const { data } = await client.post( `/comments/comment/${movieId}`, newComment, { headers: { authorization: "Bearer " + token, }, } ); return data; } catch (error) { return catchError(error); } };
后端createComment接口
exports.createComment = expressAsyncHandler(async (req, res) => { const { movieId } = req.params; const { content } = req.body; const userId = req.user._id; console.log(req.body); // verify user before comment if (!req.user.isVerified) return sendError(res, "Please verify your email first!"); if (!isValidObjectId(movieId)) return sendError(res, "Invalid Movie!"); // create and update new comment const newComment = new Comment({ user: userId, parentMovie: movieId, content, }); // save new comment await newComment.save(); res.json({ message: "New comment added!!", newComment }); });
问题分析
- 核心问题:前端调用API时未传递评论内容
前端handleSubmit函数中,调用addComment(movieId)时仅传入了movieId,但API层的addComment需要接收movieId和newComment两个参数,导致请求体为空,后端无法获取content字段。 - 冗余无效操作
提交后执行setContent(newComment)将对象赋值给字符串类型的状态变量,后续又调用setContent("")清空,属于无意义操作。
修复方案
修改前端handleSubmit函数,调用addComment时传入评论内容,并移除冗余操作:
const handleSubmit = async (e) => { e.preventDefault(); // 传递包含content的对象作为第二个参数 const { error, message } = await addComment(movieId, { content }); if (error) return updateNotification("error", error); updateNotification("success", message); // 直接清空输入框即可 setContent(""); };
验证效果
修复后,前端提交评论时,请求体将携带{ content: "用户输入的评论内容" },后端控制台会打印正确的请求体,评论内容将正常存入数据库。
内容的提问来源于stack exchange,提问作者Kelvin Henry
相关产品推荐
相关产品推荐

