1

I have a data object containing strings, booleans, arrays, objects and even Blobs like this:

enter image description here

Now I want to send this object to my Node.js server...

Using traditional fetch API or Ajax I'm unable to send the blobs and they appear like an empty object server side!

I tried to use fetch API even using FormData approach like:

Client:

const fd = new FormData();
fd.append("upload", data); // data is the object to send
fetch('/mother/new-card', {
    method: 'post',
    body: fd,
})

Server:

controller side:

router.post('/new-card', newCard);

function newCard(req, res) {
    motherService.newCard(req)
        .then(result => res.json(result))
        .catch(err => {
            console.log(err);
            res.json(err)
        });
}

Service side:

async function newCard(req) {
    console.log('req.body', req.body);
    return { success:  req.body }
}

I usually get undefined trying above methods ...

Is there any valid way to send an object with blobs in it?

Sara Ree
  • 3,417
  • 12
  • 48
  • Take a look here: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects#creating_a_formdata_object_from_scratch I don't know what `fetch` is, but that's the native web API way of sending blobs. This is a very common question with many answers already, but you'd have to do more debugging yourself, starting from something simpler, to find out the problem. – Robin De Schepper Oct 27 '21 at 11:36
  • I know how to send a single blob, that's not a big deal, I want to know how to "Send an Object with Blobs in it to server"? – Sara Ree Oct 27 '21 at 11:38
  • The web uses the `HTTP` protocol to send data, it's a language agnostic text based protocol. You can't send JavaScript objects over those without a JavaScript specific (de)serialization library on top of it. – Robin De Schepper Oct 27 '21 at 11:39
  • Sending `data` using JSON ruins the Blobs, That's why I posted a question here :) – Sara Ree Oct 27 '21 at 11:41
  • Well a blob is a binary string, you could encode and send that in the JSON: https://stackoverflow.com/questions/18650168/convert-blob-to-base64 – Robin De Schepper Oct 27 '21 at 11:43

0 Answers0