Getting an empty request data property in the api endpoint function after calling multer upload(...) method directly.
Please view a brief sample here codesandbox
The api endpoint using the multer upload method is located here: pages/api/ajax-upload.js
Thank you very much for the reproduction case!
I forked your sandbox and got it working.
This wasn't an issue with multer, but was because of how next.js parses incoming request bodies.
There were two major issues, the first is a misunderstanding about multer so I'll address that.
In your ajax-upload route, you were trying to print the values of the form you sent to the server with the following lines:
console.log("RECEIVED REQUEST FIELDS ::::", req.testFile);
console.log("RECEIVED REQUEST FILES ::::", req.description);
That's incorrect, with proper parsing of the request body (the form you sent) the description field from the form would be included in req.body at req.body.description.
Secondly, multer parses files into a field on the request object called req.file or req.files if uploading multiple files or file fields. So you can access your single upload of testFile at req.testFile, assuming the upload is successful.
The big issue here to make this work though was disabling bodyParser for that particular route in next.js.
At the bottom of your ajax-upload.js file I have added:
export const config = {
api: {
bodyParser: false
}};
According to the custom middleware docs for next.js, body parsing is on by default. I disabled it in order to allow multer to consume the form data as a stream, before it has been parsed.
Not exactly sure what the underlying issue was, but that's all the time I can invest into this today 馃憤
Thank you, @jonchurch.
After adding the config as you recommended, the description field is now appearing in req.body, and testFile is also properly loaded in req.file. I think your answer totally took care of it.
Ps. I read somewhere that the multer upload places the individual fields directly inside the request object. So I switched to accessing description and testFile values from the req object albeit unsuccessfully. But all of that is now water under the bridge.
Thanks again
Most helpful comment
Thank you, @jonchurch.
After adding the config as you recommended, the description field is now appearing in req.body, and testFile is also properly loaded in req.file. I think your answer totally took care of it.
Ps. I read somewhere that the multer upload places the individual fields directly inside the request object. So I switched to accessing description and testFile values from the req object albeit unsuccessfully. But all of that is now water under the bridge.
Thanks again