You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB+React图片加载显示undefined及404错误求助

问题:React获取MongoDB帖子时图片显示undefined,返回404错误

已将包含文本和图片的帖子存入MongoDB,但React前端获取信息时图片显示undefined,控制台返回GET http://localhost:4000/api/postblog/undefined_xxx.jpg 404。已尝试添加静态资源配置app.use("/postblog", express.static(__dirname + "/postblog")),问题仍未解决。


相关代码

1. Post模型

const mongoose = require("mongoose");
const { Schema, model } = mongoose;
const postSchema = new Schema(
  {
    title: String,
    summary: String,
    content: String,
    file: String,
  },
  {
    timestamps: true,
  }
);

const PostModel = model("Post", postSchema);

module.exports = PostModel;

2. 后端multer图片上传处理

const multer = require("multer");
const blogStorage = multer.diskStorage({
  destination: (req, file, callback) => {
    callback(null, "./api/postblog");
  },
  filename: (req, file, callback) => {
    callback(null, `${Date.now()}_${file.originalname}`);
  },
});

const postblog = multer({ storage: blogStorage });

app.post("/post", postblog.single("file"), async (req, res) => {
  const { title, summary, content } = req.body;
  const { originalname, path } = req.file;
  const newPath = path;
  const postDoc = await Post.create({
    title,
    summary,
    content,
    file: newPath,
  });
  res.json(postDoc);
});

app.get("/post/:id", async (req, res) => {
  const { id } = req.params;
  const postDoc = await Post.findById(id);
  res.json(postDoc);
});

3. 前端PostPage.js获取帖子

const PostPage = () => {

   const [postInfo, setPostInfo] = useState(null);
   const { userInfo } = useContext(UserContext);
   const { id } = useParams();
   useEffect(() => {
     fetch(`http://localhost:4000/post/${id}`).then((response) => {
       response.json().then((postInfo) => {
         setPostInfo(postInfo);
       });
     });
   }, []);

   if (!postInfo) return "";

  return (
    <div className="post-page">
      <h1>{postInfo.title}</h1>
      <time>{formatISO9075(new Date(postInfo.createdAt))}</time>
      <div className="image">
        <img src={`http://localhost:4000/${postInfo.cover}`} alt="" />
      </div>
      <div
        className="content"
        dangerouslySetInnerHTML={{ __html: postInfo.content }}
      />
    </div>
  );
}

export default PostPage

排查&解决步骤

  1. 修正字段名不匹配问题:
    后端MongoDB存储图片路径的字段是file,但前端代码中用postInfo.cover获取,直接导致undefined。将前端<img>标签的src改为http://localhost:4000/${postInfo.file}。

  2. 调整静态资源路由配置:
    后端存储的图片路径是./api/postblog/xxx.jpg,对应的访问路由需要和静态资源配置匹配。将静态资源配置改为:

    const path = require('path');
    app.use("/api/postblog", express.static(path.join(__dirname, "api/postblog")));
    

    使用path.join避免操作系统路径拼接错误,确保静态资源目录正确映射。

  3. 验证返回数据完整性:
    在前端fetch的回调中添加console.log(postInfo),确认后端返回的file字段值是否为完整的相对路径(如api/postblog/123456_xxx.jpg)。

  4. 检查文件存储状态:
    确认./api/postblog目录存在,且上传的图片确实保存在该目录下,文件名与数据库中存储的file字段值一致。


内容的提问来源于stack exchange,提问作者Belas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:17:37