I have tried splitting an arrow function to two, in-order to try and pass a few outer variables into the inner-one between the two (in terms of scope).
This is the original function:
app.post('/single', upload.single('image'), (req, res, next) => {
res.status(200).send('File uploaded successfully.')
});
And this is the new, splitted one:
app.post('/single', (req, res, next) => {
upload.single('image', () => {
console.log('2');
res.status(200).send('File uploaded successfully.')
}),
});
The problem is, on the second example, console.log('2') is never being called, and the picture upload process isn't too? (although it is only nested).
What may cause that?
Thank you.
The problem is, on the second example, console.log('2') is never being called, and the picture upload process isn't too? (although it is only nested). What may cause that?
upload.single('image')
is middleware. That means when you call it, it just returns another function and that function expects to be passed req
, res
and next
as the arguments.
So, what you're doing with:
upload.single('image', () => {... });
Will just return a function that is never called and it will never call the passed callback because that's not how upload.single()
was designed to work.
If you really wanted to call it manually (which I do not recommend), you'd have to do something like this:
app.post('/single', (req, res, next) => {
upload.single('image')(req, res, (err) => {
if (err) {
return next(err);
}
console.log('2');
res.status(200).send('File uploaded successfully.')
}),
});
Where you call upload.single()
to get the middleware function and then you call that function and pass it the desired (req, res, next)
, but you substitute your own callback for the next
argument and then in that callback you check to see if next
by the middleware was called with an error or not and continue only if it wasn't.