cft

Multer — req.body null object when send file with other field string using formData

Solve req.body null object when send file with other field string using formData


user

Muhammad Hizbullah

a year ago | 4 min read

I was work in some project that built with NextJS as Front End and ExpressJS as Back End, when i create Rest API for upload image, in my case it’s Banner data. The Endpoint was tested using Insomnia and the result is work perfectly, but when i implement it at frontend code, i got req.body like a below in my multer function:

// result of console.log(req.body)

[Object: null prototype] {}

// multer upload function

const multer = require("multer");

const slugify = require("slugify");

const randomstring = require("randomstring");

const fileStorage = multer.diskStorage({

destination: (req, file, callback) => {

console.log(req.body);

callback(null, './public/images');

},

filename: (req, file, callback) => {

const randomString = randomstring.generate({

length: 6

})

console.log(req.body);

const slug = `${slugify(req.body.name)}-${randomString}`;

req.slug = slug;

callback(null, `${slug}${path.extname(file.originalname)}`)

}

})

And this my frontend request

// SEND DATA FROM FRONTEND USING NEXTJS

let formData = new FormData()

formData.append('image', bannerImage)

formData.append('name', bannerName)

await axios({

method: 'post',

url: '/api/v1/admin/banner',

data: formData,

headers: {

"Content-Type": "multipart/form-data",

}

});

And this request using insomnia (it’s work)

In several hours i explore and try to fixing it. finally, i found the solution after read a multer documentation here.

How I solved it:

When we look at both of frontend code and insomnia request implementation, there the order of field name (string) and image (file) is different. Then i was reorder append data in my frontend code to below code:

// SEND DATA FROM FRONTEND USING NEXTJS// I WAS REORDER APPEND DATA WITH FILE TYPE MUST BE LAST ORDER

let formData = new FormData()

formData.append('name', bannerName)

formData.append('image', bannerImage)

await axios ({

method: 'post',

url: '/api/v1/admin/banner',

data: formData,

headers: {

"Content-Type": "multipart/form-data",

}

});

Then, in console.log(req.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 hh' }

[Object: null prototype] { name: 'gg hh' }

[Object: null prototype] { name: 'banner 3 gg' }

[Object: null prototype] { name: 'banner 3 gg' }

Conclusion

When data just file, you dont worry about the order of field data.But when you have another data like string or number, you must pass them at second order or more, dont add file at first order.

I hope this can help other people, i’m sorry about my english quality.

Upvote


user
Created by

Muhammad Hizbullah


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles