question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Object: null prototype] {} for req.body

See original GitHub issue

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

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:5
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
serp-yacommented, Dec 9, 2020

Hi again! I’m solved issue on my side. I was use express-form-data for parsing form-data and this middleware was cut file data from request object and puted in to new field req.files

Now I updated Express to ^4.17.1 version and I don’t need any plugiun anymore for parsing form-data

UPD: problem don’t solved, because any another route miss form-data values

UPD2: this is a really strange issue… If we are use any middleware on the application level AND use multer middleware instance on the route level, we loose a body field and file field on our request object inside router handler.

And we can’t to use any multer instance on application level (rule from multer docs) or any another form-data handling middleware for support another routes, who use form-data values from the body field…

So a reason question - how to use multer to support form-data values on the all routes in our applications?.

0reactions
metrocodingcommented, Jun 6, 2021

@richardscheid are you sure that you are running into this exact issue? Celebrate seems to use Joi which should work with prototypeless objects (see sideway/joi#693).

If you are, I would recommend opening an issue on Celebrate, I don’t see why it shouldn’t work on prototypeless objects…

Hi, I have data in my req.body and I wanna access it before upload then set storage base on req.body with storageMaker function, what workaround you suggest?

export default () => {
    return function (req: Request, res: Response, next: NextFunction) {
        const storage = storageMaker(req.body);
        let upload = multer({
            storage: storage,
            fileFilter: mimeFilter,
        }).single("profile_picture");

        upload(req, res, function (err: any) {
            if (err) {
                res.status(500).send(
                    new ApiResponseResult(
                        false,
                        null,
                        [
                            new ResponseMessage(
                                ResponseMessageType.ERROR,
                                "Error in uploading file"
                            ),
                        ],
                        err
                    )
                );
                return;
            }
            next();
        });
    };
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

how to fix [Object: null prototype] { title: 'product' }
It initializes a new object with Object.prototype and assigns all the properties of req.body to it. Share.
Read more >
JavaScript and object with null prototype - LinkedIn
Object.create(null) is done to prevent collision between the prototypical keys and ones own named keys. Perhaps that is what the library authors ...
Read more >
Multer — req.body null object when send file with other field ...
body) in multer function, i got a value of req.body with object inside. // result of console.log(req.body) [Object: null prototype] { name: 'gg ......
Read more >
how to fix [Object: null prototype] { title: 'product' } - YouTube
I get some problem and my terminal showed me below explanationbody-parser deprecated undefined extended: provide an extended option at the ...
Read more >
node js req.body object null prototype
Node prototype is null or not an object ... If it would just be "a regular object" it wouldn't be: req.body.toString(); There is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found