Converting FormData string keys to accessible Json Object

Viewed 120

My frontend (JS) is sending a request to my backend (Node Typescript) with FormData (because the FormData consist of images too) as below:-

FormData

In my Node project, I am currently using express-fileupload (npm) so when I log the req.body the result I get is this:-

Node Result

This makes it hard to access the object as I have to do req.body['items[0][item][id]'] instead of req.body.items[0].item.id. Is there a way to easily format the req.body into accessible like a JSON object like below?

{
    orderNo: "A00006",
    items: [
        {
            item: {
                _id: "60dfkwakawn1",
                status: 1,
                model: {
                  ...
                },
                ...
            }
            ...
        }
    ],
    ...
}
1 Answers

What I have done before is to turn my non-file data into a JSON string on the client side before injecting it into the FormData.


let fd = new FormData();
/* Non-file data you need to send to the server. */
fd.append('order', JSON.stringify({orderNo: "A00006", items: [{item: {_id: "60dfkwakawn1"}]}));
/* File object from my file dom element in uploadEl. */
fd.append('myFile', uploadEl.files[0]);
/* Submit the form data, fd, to the server with whatever you are using on the client. */

On the server then you need to manually pull values from the req and convert it back to any object:

let order = JSON.parse(req.body.order);
Related