MongoDB博客文章无法通过API加载至首页,数据显示undefined
问题描述
MongoDB中已配置博客文章,尝试拉取到首页展示时,所有待获取数据均显示为undefined;页面可正常添加新文章,但已有文章无法被拉取。控制台出现如下错误:
GET http://localhost:3003/undefined 404 (Not Found)
相关代码文件
home.js
$(document).ready(() => { $.get("/api/posts", results =>{ outputPosts(results, $("\.postsContainer")); }) }) function outputPosts(results, container){ container.html(""); results.forEach(result => { var html = createPostHtml(result) container.append(html); }) if(results.length == 0){ container.append("<span class='noResults'> no results found.</span>") } }
Post.js
const express = require('express'); const app = express(); const router = express.Router(); const bodyParser = require("body-parser") const User = require('../../schema/userSchema'); const Post = require('../../schema/PostSchema'); app.use(bodyParser.urlencoded({ extended: false })); router.get("/", (req,res,next) => { Post.find() .then(results => res.status(200).send(results)) .catch(error => { console.log(error); res.sendStatus(400); }) }) router.post("/", async(req,res,next) => { if(!req.body.content){ console.log("Content param not sent with request"); return res.sendStatus(400); } var postData = { content: req.body.content, postedBy: req.session.user } Post.create(postData) .then(async newPost => { newPost = await User.populate(newPost, { path: "postedBy"}) res.status(201).send(newPost); }) .catch(error => { console.log(error); res.sendStatus(400); }) }) module.exports = router;
common.js
$.post("/api/posts",data,postData => { var html = createPostHtml(postData); console.log(html); $("\.postsContainer").prepend(html); textbox.val(""); button.prop("disabled", true); }) }) function createPostHtml(postData){ var postedBy = postData.postedBy; var displayName = postedBy.firstName + " " + postedBy.lastName; var timestamp = " to do later"; return `<div class='post'> <div class='mainContentContainer'> <div class='userImageContainer'> <img src='${postedBy.profilePic}'> </div> <div class='postContentContainer'> <div class='header'> <a href='/profile/${postedBy.username}' class='displayName'>${displayName}</a> <span class='username'>@${postedBy.username}</span> <span class='date'>${timestamp}</span> </div> <div class='postBody'> <span>${postData.content}</span> </div> <div class='postFooter'> <div class="postButtonContainer"> <button> <i class='far fa-comment'></i> </button> </div> <div class="postButtonContainer"> <button> <i class='far fas-retweet'></i> </button> </div> <div class="postButtonContainer"> <button> <i class='far fa-heart'></i> </button> </div> </div> </div> </div> </div>`; }
问题根源
- GET接口未关联用户数据:获取已有文章的
/api/posts接口仅查询Post集合,未像POST接口那样用User.populate()关联postedBy字段的用户信息,导致返回的post对象中postedBy是MongoDB的ObjectId而非完整用户对象,前端访问postedBy.firstName等属性时返回undefined。 - DOM选择器转义错误:
home.js和common.js中的$("\.postsContainer")多了不必要的反斜杠转义,导致无法正确选中DOM容器,渲染失败。 - 字段缺失无兜底处理:若数据库中部分用户无
profilePic等字段,会生成src='undefined'的图片请求,触发404错误。
修复方案
1. 完善GET接口的用户关联
修改Post.js中的GET路由,添加populate方法关联用户数据:
router.get("/", (req,res,next) => { Post.find() .populate("postedBy") // 关联postedBy字段对应的用户文档 .then(results => res.status(200).send(results)) .catch(error => { console.log(error); res.sendStatus(400); }) })
2. 修正DOM选择器
home.js中修改选择器:
// 原代码 outputPosts(results, $("\.postsContainer")); // 修改后 outputPosts(results, $(".postsContainer"));
common.js中修改选择器:
// 原代码 $("\.postsContainer").prepend(html); // 修改后 $(".postsContainer").prepend(html);
3. 为前端字段添加兜底处理
修改common.js的createPostHtml函数,为可能缺失的字段设置默认值,避免undefined:
function createPostHtml(postData){ var postedBy = postData.postedBy || {}; // 兜底空对象防止报错 var firstName = postedBy.firstName || ""; var lastName = postedBy.lastName || ""; var displayName = `${firstName} ${lastName}`.trim(); var profilePic = postedBy.profilePic || "/default-avatar.png"; // 设置默认头像路径 var username = postedBy.username || "unknown-user"; var content = postData.content || ""; var timestamp = " to do later"; return `<div class='post'> <div class='mainContentContainer'> <div class='userImageContainer'> <img src='${profilePic}'> </div> <div class='postContentContainer'> <div class='header'> <a href='/profile/${username}' class='displayName'>${displayName}</a> <span class='username'>@${username}</span> <span class='date'>${timestamp}</span> </div> <div class='postBody'> <span>${content}</span> </div> <div class='postFooter'> <div class="postButtonContainer"> <button> <i class='far fa-comment'></i> </button> </div> <div class="postButtonContainer"> <button> <i class='fas fa-retweet'></i> <!-- 修正图标类名错误 --> </button> </div> <div class="postButtonContainer"> <button> <i class='far fa-heart'></i> </button> </div> </div> </div> </div> </div>`; }
内容的提问来源于stack exchange,提问作者Mitchell
相关产品推荐
相关产品推荐

