I build an eCommerce App with an admin dashboard, and I have faced an issue when adding or updating an image for every product, and can’t handle this error. the images are being stored in the database as a URL link and being stored in the uploads folder, but not being displayed in the table, and that’s what appears in the console on the browser.
this error shows in the console “Failed to load resource: the server responded with a status of 404 (Not Found)“. and can’t handle with this issue
Beurer-BEU-FC40-1638202407224.png:1 GET http://localhost:3000/public/uploads/Beurer-BEU-FC40-1638202407224.png 404 (Not Found)
this is the server code for the location of images (uploads) in app.js
app.use('../public/uploads', express.static(__dirname + '../public/uploads'))
And this is the multer code for image files.
// file types
const FILE_TYPE_MAP = {
'image/png': 'png',
'image/jpg': 'jpg',
'image/jpeg': 'jpeg'
};
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const isValid = FILE_TYPE_MAP[file.mimetype];
let uploadError = new Error('invalid image type');
if (isValid) {
uploadError = null;
}
cb(uploadError, 'public/uploads');
},
filename: function (req, file, cb) {
const fileName = file.originalname.split(' ').join('-');
const extension = FILE_TYPE_MAP[file.mimetype];
cb(null, `${fileName}-${Date.now()}.${extension}`);
}
});
const uploadOptions = multer({ storage: storage });
And this is the API code for posting a product with an image.
router.post(`/`, uploadOptions.single('image'), async (req, res) => {
// validate the category of product
const category = await Category.findById(req.body.category);
if (!category) return res.status(400).send('Invalid Category');
// validate the image file of the product
const file = req.file;
if (!file) return res.status(400).send('No image in the request');
const fileName = file.filename;
const basePath = `${req.protocol}://${req.get('host')}/public/uploads/`;
let product = new Product({
name: req.body.name,
description: req.body.description,
richDescription: req.body.richDescription,
image: `${basePath}${fileName}`,
brand: req.body.brand,
price: req.body.price,
category: req.body.category,
countInStock: req.body.countInStock,
rating: req.body.rating,
numReviews: req.body.numReviews,
isFeatured: req.body.isFeatured
});
product = await product.save()
if(!product) return res.status(404).send({success:false, data: message, message: "the product not found"})
res.status(200).send({ success: true, data: product })
})
Could anyone help me?