我正在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
中写什么?