[Object: null prototype] {} for req.body
- Dominant language
- JavaScript
- Stars
- 12.1k
- Forks
- 1.1k
- Avg merge
- 8d 2h
- Merged PRs (30d)
- 21
Description
First I used upload function inside Controller.js(code given below) as per the GitHub multer tutorial and its working but the problem is I have to write the same code again and again in each js file where I'm using multer to upload file. For code reusability I'm trying to implement in the following way
I have created a file where in class method I'm using multer upload function. Files are getting uploaded successfully but the problem is I'm not able to use the **req** object after I call this class method. Below i m pasting the code and output.
**FileStorage.js**
```
const multer = require('multer');
const path = require('path');
class FileStorage{
storeFileUsingMulter(req,res,folderName,fileFieldName){
try{
const storage = multer.diskStorage({
destination : function(req , file ,cb){
let dest = path.join(path.resolve("../"),"\\FileStorage\\",folderName);
cb(null,dest);
},
filename: function(req,file,cb){
cb(null,file.originalname);
}
});
const upload = multer({storage: storage}).single(fileFieldName);
let result;
upload(req,res,(err)=>{
if(err)
throw err;
else{
console.log(req.body);
result = req;
console.log(result.body); //printing the req.body object
}
});
console.log(result); //printing undefined
return result;
}
catch(err){
console.log(err);
throw err;
}
}
}
module.exports = FileStorage;
```
**Controller.js**
```
const FileStorage = require('../functions/FileStorage');
const fileStorage = new FileStorage();
class ProfileController{
async setUserProfile(req,res){
try{
await fileStorage.storeFileUsingMulter(req,res,"Profiles","profile");
console.log("setUsrProfile()");
console.log(req.body); //printing [Object: null prototype] {}
res.send("success");
}
catch(err){
let r = {
status : status[2],
msg : err.message
}
console.log(err);
res.send(r);
}
}
}
module.exports = ProfileController;
```
> **Point to note** : Even if function is called first the other code is getting executed first
> console.log("setUsrProfile()");
console.log(req.body);
res.send("success");
gets exectued before `await fileStorage.storeFileUsingMulter(req,res,"Profiles","profile");`
**Ouptut**
```
setUsrProfile()
[Object: null prototype] {}
[Object: null prototype] {
dob: '****',
gender: '***',
****: '***',
****: '***'
}
[Object: null prototype] {
dob: '****',
gender: '***',
****: '***',
****: '***'
}
undefined
```
Please let me know if there is any solution. I'm trying to find solution from last 2 days but nothing is working
Contributor guide
Assessment
This issue has not been assessed yet.