I am trying to make a get request to receive the posts that exist in my MongoDB. I am using multer middleware and am struggling to display the images in the frontend.
My backend code looks like: (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
This code is tied to app.use('/feed', feedRoute)
and gets called. My get request retrieves the data in my database correctly as:
[
{
_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
}
]
However, I am not able to understand how to use the art_image
file path to display it in front end. What should I write in the src
of the img
tag?
You need to serve uploaded files from the server.
You could serve entire uploads
folder as a static folder:
app.use(express.static(path.join(__dirname, 'uploads')));
and then add art_image
value to the src
:
<img src="1685668751687-event_juntion.png" />
(you can also add a virtual path):
app.use('/images', express.static(path.join(__dirname, 'uploads')));
<img src="images/1685668751687-event_juntion.png" />
Or, you could serve each file with sendFile upon each request, by adding a new route, which would take file name via req.params, and that approach wouldn't make the whole uploads folder accessible:
app.get("/images/:image", (req, res) => {
res.sendFile(path.join(__dirname, 'uploads', req.params.image));
});
<img src="images/1685668751687-event_juntion.png" />
See more which option would suit you: