Open
Description
I'm working with very simple file upload feature using Express.js & Multer.
This is my multer middleware code:
const path = require('path')
const multer = require('multer')
const storage = multer.diskStorage({
destination: function (req, file, cb) {
// Set the destination folder for uploaded files
cb(null, './public/uploads/')
},
filename: function (req, file, cb) {
// Generate a unique filename to avoid naming conflicts
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9)
const originalFileExtension = path.extname(file.originalname)
const filename = file.fieldname + '-' + uniqueSuffix + originalFileExtension
cb(null, filename)
},
})
const upload = multer({
storage: storage,
limits: { fileSize: 100 * 1024 * 1024 },
fileFilter: function (req, file, cb) {
const allowedTypes = /pdf|xls|zip|rar|jpg/
const fileType = path.extname(file.originalname).toLowerCase()
if (allowedTypes.test(fileType) === false) {
const err = new Error('File extensions is not allowed.')
err.status = 500
err.name = 'FileValidationError'
cb(err, false)
}
cb(null, true)
},
})
module.exports = upload
This is my error handler middleware:
// wrap unathorized error
router.use((err, req, res, next) => {
if (['UnauthorizedError', 'FileValidationError'].includes(err.name)) {
return res.status(err.status).json({
error: true,
code: err.status,
message: err.message,
})
}
next(err)
})
When I hit this endpoint from Frontend (React.js) using Axios and FormData. I got never ending 'pending' request and I dont know why this is happen with this simple code. The expected results is custom JSON response should be returned.
After a minutes searching, I found that if I remove the 'FileValidationError' from error handler logic or using this code:
if (err instanceof multer.MulterError) {}
The request is not pending and it returned response the Error() instance.
But, this behavior only happens in the Frontend side. I tested with Postman and the request looks fine.
Can someone tell me If I do something wrong in this situation?
Metadata
Metadata
Assignees
Labels
No labels