JavaJedi JavaJedi - 6 months ago 79
Node.js Question

POST request via requestJS to send Array of JSON Objects and image files

I'm building REST API with NODEjs, using Express routers and Multer middleware to handle multiple body data and files.

My endpoint route 127.0.0.1/api/postData expects: json data with fields, one of which is array of json objects (I'm having nested mongoose schema) and 2 named images (png/jpg).

I need to send Post request via cURL with the following 5-object data structure:

name String
description String
usersArray Array of json objects like: [{"id": "123"}, {"id": "456}]
imgIcon Png/Image providing /path/to/imageIcon.png
imgHeader Png/Image providing /path/to/imageHeader.png


Any idea how to write this request with the help of request.js node http request library ?

Answer

Try the following:

request.post({
    url:'http://127.0.0.1:7777/api/postData'
    , formData: formData
    , qsStringifyOptions : {
        arrayFormat : 'brackets' // [indices(default)|brackets|repeat]
    }
}, function (err, httpResponse, body) {
 // do something...
}

I found three options for arrayFormat in https://www.npmjs.com/package/qs (used by https://www.npmjs.com/package/request):

'indices' sends in postbody: (this is the default case)
usersArray%5B0%5D%5Bid%5D=a667cc8f&usersArray%5B1%5D%5Bid%5D=7c7960fb
decoded:
usersArray[0][id]=a667cc8f&usersArray[1][id]=7c7960fb

'brackets' sends in postbody:
usersArray%5B%5D%5Bid%5D=a667cc8f&usersArray%5B%5D%5Bid%5D=7c7960fb
decoded:
usersArray[][id]=a667cc8f&usersArray[][id]=7c7960fb

'repeat' sends in postbody:
usersArray%5Bid%5D=a667cc8f&usersArray%5Bid%5D=7c7960fb
decoded:
usersArray[id]=a667cc8f&usersArray[id]=7c7960fb

these are three different ways to serialize arrays before posting. Basically it depends on the receiving end how these need/can be formatted. In my case it helped to use 'brackets'

Comments