Newcomer to nodejs.
I write the code below and use thunder client to test, finding an error: 500.
Image storage engine
const storage = multer.diskStorage({
destination: './upload/images',
filename: (req, file, cb)=>{
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({storage: storage})
// Create upload endpoint for images
app.use('/images', express.static('upload/images'))
app.post("/upload", upload.single('product'), (req, res)=>{
res.json({
success: 1,
image_url: `http://localhost:${port}/images/${req.file.filename}`
})
})
This is the error information.
TypeError: Cannot read properties of undefined (reading 'filename')
at /home/pp/Desktop/E-Commerce/backend/index.js:37:62
at Layer.handle [as handle_request] (/home/pp/Desktop/E-Commerce/backend/node_modules/express/lib/router/layer.js:95:5)
at next (/home/pp/Desktop/E-Commerce/backend/node_modules/express/lib/router/route.js:149:13)
at Immediate._onImmediate (/home/pp/Desktop/E-Commerce/backend/node_modules/multer/lib/make-middleware.js:53:37)
at process.processImmediate (node:internal/timers:478:21)
If I remove image_url, the test can be passed. I am sure other part of the code is correct, because if I remove the code above, everything goes fine.
But actually I am wondering if multer is actually working, because when I add an output in multer.diskStorage() and execute the code below, there is no "hello" on the console. So I think multer.diskStorage() function is not called at all.
Image storage engine
const storage = multer.diskStorage({
destination: './upload/images',
filename: (req, file, cb)=>{
console.log("hello")
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({storage: storage})
// Create upload endpoint for images
app.use('/images', express.static('upload/images'))
app.post("/upload", upload.single('product'), (req, res)=>{
res.json({
success: 1,
})
})
Anyone met such problem before? Thanks a lot!