I am using MERN to create simple eCommerce I am facing error when i am in production mode. The file uploads on the specified folder but don't get load on front-end.
Server.js
import path from 'path'
import express from 'express'
import dotenv from 'dotenv'
const __dirname = path.resolve()
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '/frontend/build')))
app.get('*', (req, res) =>
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
)
} else {
app.get('/', (req, res) => {
res.send('Api running....')
})
}
app.use('/uploads', express.static(path.join(__dirname, '/uploads')))
Upload routes and code
import path from 'path'
import express from 'express'
import multer from 'multer'
const router = express.Router()
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, '/uploads')
},
filename(req, file, cb) {
cb(
null,
`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
)
},
})
function checkFileType(file, cb) {
const filetypes = /jpg|jpeg|png/
const extName = filetypes.test(path.extname(file.originalname).toLowerCase())
const mimeType = filetypes.test(file.mimetype)
if (extName && mimeType) {
return cb(null, true)
} else {
cb('Images only with jpg, jpeg, png ')
}
}
const upload = multer({
storage,
fileFilter: function (req, file, cb) {
checkFileType(file, cb)
},
})
router.post('/', upload.single('image'), (req, res) => {
res.send(`/${req.file.path}`)
})
export default router
When i inspect the file it says on the src the image cant load check the image=>
Now when i am in development mode the same code works as expected and the image loads.
What might the possible error please help me. Thank you in Advance.
Your production server is not meant to store files because that will lead to increase in consumption of server resources. So it will automatically delete any files/images that you have uploaded to the production server.
And why would you want to store files on production server, just use a database or file storage system like s3 bucket.