我正在try 发出GET请求,以接收我的MongoDB中存在的帖子.我正在使用Multer中间件,很难在前端显示图像.

我的后端代码如下所示: (posts.js)

import express from "express";
import multer from "multer";
import Posts from "../models/posts.js";


const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({ storage: storage });

const router = express.Router();

router.route("/create").post(upload.single('file'), async (req,res)=>{
  try {
    const post = new Posts({
      title: req.body.title,
      description: req.body.description,
      amt: req.body.amt,
      artist_name: req.body.artist_name,
       // Use fileType instead of req.body.type
      
      art_image: req.file.filename,
    });

    const savedPodcast = await post.save();
    res.status(201).json(savedPodcast);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal server error" });
  }
});

router.route("/feed").get( async (req, res) => {
  try {
    const getPosts = await Posts.find();
    console.log(getPosts)
    res.json(getPosts);
   
  } catch (error) {
    res.status(500).json({ message: "Error fetching posts", error });
  }
});


export default router


此代码绑定到app.use('/feed', feedRoute)并被调用.我的GET请求正确地检索数据库中的数据,如下所示:

[
  {
    _id: new ObjectId("6479438fdf4ff1fc5cf2eab8"),      
    artist_name: 'sad',
    title: 'gfds',
    description: 'adf',
    amt: '234',
    reportCount: 0,
    upvote: 0,
    createdAt: 2023-06-02T01:19:02.297Z,
    art_image: '1685668751687-event_juntion.png',       
    apply_watermark: true,
    __v: 0
  }
]

然而,我不能理解如何使用art_image文件路径在前端显示它.我应该在img标签的src中写什么?

推荐答案

您需要提供从服务器上传的文件.

您可以将整个uploads文件夹作为static folder:

app.use(express.static(path.join(__dirname, 'uploads')));

然后将art_image值添加到src:

<img src="1685668751687-event_juntion.png" />

(您还可以添加虚拟路径):

app.use('/images', express.static(path.join(__dirname, 'uploads')));
<img src="images/1685668751687-event_juntion.png" />

或者,您可以在每次请求时 for each 文件添加sendFile个文件,方法是添加一个新的路径,它将通过req.params获取文件名,而这种方法不会使整个上传文件夹可访问:

app.get("/images/:image", (req, res) => {

    res.sendFile(path.join(__dirname, 'uploads', req.params.image));

});
<img src="images/1685668751687-event_juntion.png" />

了解更多信息哪个选项更适合您:

express.static vs. res.sendFile

Mongodb相关问答推荐

基于另一子文档更改子文档的引用

MongoDB:删除键上有条件的对象元素

在MogoDB中按时间间隔分组、统计文档和获取间隔时间

在MongoDB中是否可以按递增顺序更新多个文档?

MongoDB与合并对象聚合

当日期和时间在不同键的字符串中时,Mongo 查询过滤今天的数据

MongoDB:检测所有重叠事件(开始/结束日期)?

使用golang中的过滤器从mongodb复合集合中获取所有数据

DB 中的引用对象在 GraphQL 查询中返回 null

使用新字段插入数据或使用 updateOne mongodb 有条件地更新

使用 Node.js 通过 SSL 连接到 MongoDB

查找对象是否在预保存钩子mongoose中更改

SELECT 字段 AS `anothername` 的 mongodb 等效项

mongodb,pymongo,aggregate聚合给出奇怪的输出

如何在 MongoDB 集合中查找与给定条件匹配的文档和单个子文档

带有 jQ​​uery Ajax/JSON 前端的 MongoDB 或 CouchDB 中间件

TypeError: object of type 'Cursor' has no len()

MongoDB服务器仍然可以在没有凭据的情况下访问

无法使用命令写入模式错误,降级到兼容模式

使用 Mongoose ORM 的杀手锏是什么?