Friday 21 April 2017

Multipart NodeJS request with Object in it

How would you send a multipart request from nodeJs to java server? This request have to contain String, Object and Stream. This what I put to gether using request promise npm module:

var options = {
    method: req.method,
    baseUrl: PROTOCOL + HOST + PORT,
    uri: req.originalUrl,
    formData: {
        metadata: JSON.stringify(newBody),
        folderUUID: 'wqer-4124-asdf-7899',
        file: fs.createReadStream(__dirname + '/attachments/ssipky.jpg')
    },
    headers: {
        /* 'content-type': 'application/x-www-form-urlencoded' */ // Set automatically
        'Content-Type': 'multipart/form-data',
        'Accept': 'text/plain'
    }
};

rp(options)
    .then(function (body) {
        console.log(body);
        // POST succeeded...
    })
    .catch(function (err) {
        console.log(err);
        // POST failed...
    });

problem is that with form-data module, you can send only Buffers, Streams and Strings not json object notation.

so the request looks like this: metadata as text

but should look like this (sent by Insomnia): metadata as object

When I stringify metadata object I can not receive it as strong-typed Metadata object in jersey2 endpoint, it maps just as String parameter on the server.

So, how should I send multipart request containing text, file and object form NodeJS?

Thanks!



via greengold

No comments:

Post a Comment