Wednesday, 5 April 2017

NodeJs querystring.stringify not working with Object

I am working currently on a project that requires to send custom GET HTTP requests.

I am using the default querystring builder : the Documentation

const querystring = require('querystring');

The problem is for Object (probably also for empty array) such as

extendTypes={}  

is serialiazed as :

extendTypes=

The expected result :

extendTypes={}

or its URI encoded version :

extendTypes%3D%7B%7D

So , how can I ever hope to do that ? If It is impossible with the in-builded module, which one could do what I want.

Here is my full code if you want :

function generateGetRequest(dataMap, url) {

    let queryParams = {};
    let uriParams = {};

    for (let [key, value] of dataMap) {

        // if value is an object or an array
        if (value instanceof Object || value instanceof Array) {
            uriParams[key] = value;
        } else {
            // param working for superagent
            queryParams[key] = value;
        }

    }
    let queryParamsUri = querystring.stringify(uriParams);
    console.log(queryParamsUri);
    let finalUrl = url + ( (Object.keys(uriParams).length > 0) ? "?" + queryParamsUri : "");
}



via jacques y

No comments:

Post a Comment