How to use the stringify function from querystring

Find comprehensive JavaScript querystring.stringify code examples handpicked from public code repositorys.

querystring.stringify is a built-in Node.js module that converts a JavaScript object into a query string.

135
136
137
138
139
140
141
142
143
144
let result = {};

try {
  const discovery = await utils.getOidcDiscovery();
  const response = await axios.post(discovery.token_endpoint,
    qs.stringify({
      client_id: config.get('oidc:clientId'),
      client_secret: config.get('oidc:clientSecret'),
      grant_type: 'refresh_token',
      refresh_token: refreshToken,
fork icon2
star icon1
watch icon7

+ 5 other calls in file

6
7
8
9
10
11
12
13
14
15
16
17
18


axios.defaults.baseURL = 'http://localhost:' + serverPort;


// Replace default serializer with one that works with Joi validation
axios.defaults.paramsSerializer = function(params) {
  return qs.stringify(params);
};


function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
fork icon1
star icon0
watch icon2

How does querystring.stringify work?

querystring.stringify is a built-in Node.js module method that serializes JavaScript objects into URL-encoded query strings by encoding their property names and values. This method takes two parameters: the object to be serialized and an optional parameter that specifies the delimiter and separator. If no delimiter and separator are provided, it defaults to & and = respectively. The output of this method is a string that represents the serialized object in the form of a URL query string.

221
222
223
224
225
226
227
228
229
230
async getPrayerTimeUrl() {
    return await this.getDB().then(result => result.get(prayerTimePaths.prayerTimeUrl).value());
}
buildPrayerAPIQueryString(url, prayerSettings, prayerLocation, date) {
    let uri = `${url}/${utility_1.DateUtil.getYear(date)}/${utility_1.DateUtil.getMonth(date)}`;
    let param = qs.stringify({
        //uri: url,
        // uri: `${url}/${DateUtil.getYear(date)}/${DateUtil.getMonth(date)}`,
        headers: {
            'User-Agent': 'Homey-Assistant'
fork icon0
star icon1
watch icon1

423
424
425
426
427
428
429
430
431
432
    midnightMode: 0,
    timezonestring: "Asia/Riyadh",
    latitudeAdjustmentMethod: 3,
    tune: "0,0,0,0,0,0,0,0,0"
});
let params2 = qs.stringify({
    uri: `${uri}/${utility_1.DateUtil.getYear(date)}/${utility_1.DateUtil.getMonth(date)}`,
    headers: {
        'User-Agent': 'Homey-Assistant-v2'
    },
fork icon0
star icon1
watch icon1

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const querystring = require("querystring");

const params = {
  name: "John",
  age: 30,
  city: "New York",
};

const queryString = querystring.stringify(params);

console.log(queryString); // output: "name=John&age=30&city=New%20York"

In this example, querystring.stringify is used to convert an object params into a query string format. The resulting string queryString contains the key-value pairs from the object as a sequence of URL-encoded key-value pairs separated by '&' characters.

78
79
80
81
82
83
84
85
86
87
    data.postData.text = ''
  } else {
    data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})

    // always overwrite
    data.postData.text = qs.stringify(data.postData.paramsObj)
  }
} else if (some([
  'text/json',
  'text/x-json',
fork icon0
star icon0
watch icon1

+ 2 other calls in file

75
76
77
78
79
80
81
82
83
84
	log.debug('Received string body');
	this.generateMessage = () => this.params.body;
} else if (typeof this.params.body == 'object') {
	log.debug('Received JSON body');
	if (this.params.contentType === 'application/x-www-form-urlencoded') {
		this.params.body = qs.stringify(this.params.body);
	}
	this.generateMessage = () => this.params.body;
} else if (typeof this.params.body == 'function') {
	log.debug('Received function body');
fork icon0
star icon0
watch icon0

105
106
107
108
109
110
111
112
113
114

/**
 * @returns {{}}
 */
async _fetchBalances() {
    const query = querystring.stringify({
        accessKey: this.getClientCredentials().apiKey,
        nonce: Date.now(),
    });
    const path = 'api/v1/fund/allAccount';
fork icon0
star icon0
watch icon1

+ 11 other calls in file

315
316
317
318
319
320
321
322
323
324
    statusCallback: statusCallBack,
    signature: signature,
  });
}

return querystring.stringify({
  from: sender,
  to: receiver,
  templateId: templateId,
  templateParas: templateParas,
fork icon0
star icon0
watch icon1

+ 9 other calls in file

77
78
79
80
81
82
83
84
85
86
87
88


const verifyLinkedInToken = async (resData) => {
    return new Promise(async (resolve, reject) => {
        try {


            const resp = await Axios.post('https://www.linkedin.com/oauth/v2/accessToken', stringify({
                grant_type: "authorization_code",
                code: resData.tokenId,
                redirect_uri: resData.redirectUri,
                client_id: process.env.LINKED_IN_CLIENT_ID,
fork icon0
star icon0
watch icon1

167
168
169
170
171
172
173
174
175
176
  const query = querystring.stringify({ "message": "username invalid" });
  res.redirect('./?' + query);
} // WRONG USER
if (dbResponse[0] == 1) {
  console.log("LOGIN ATTAMPTED WITH WRONG PASSWORD")
  const query = querystring.stringify({ "message": "password invalid" });
  res.redirect('./?' + query);
} // WRONG PASS
if (dbResponse[0] == 2) {
  const token = generateAccessToken({ user: user });
fork icon0
star icon0
watch icon1

227
228
229
230
231
232
233
234
235
236
237
238
239
    // 'stripe_user[state]': req.user.city || undefined,
  });
  console.log("Starting Express flow:", parameters);
  console.log("Printing the body:", req.query);


  res.redirect(STRIPE_AUTHORIZE_URI + "?" + querystring.stringify(parameters));
});




app.get("/token", async (req, res) => {
fork icon0
star icon0
watch icon1

64
65
66
67
68
69
70
71
72
73
  if (sockPort) resourceQuery.sockPort = sockPort;
  if (sockProtocol) resourceQuery.sockProtocol = sockProtocol;
}

// We don't need to URI encode the resourceQuery as it will be parsed by Webpack
const queryString = querystring.stringify(resourceQuery, undefined, undefined, {
  /**
   * @param {string} string
   * @returns {string}
   */
fork icon0
star icon0
watch icon1

30
31
32
33
34
35
36
37
38
39
  method: "post",
  url: "http://localhost:9103/intelliq_api/login",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
  data: qs.stringify({
    username: options.username,
    password: options.passw,
  }),
};
fork icon0
star icon0
watch icon1

+ 4 other calls in file

445
446
447
448
449
450
451
452
453
454
  }
}
// Create document
request.put({
  url: prefs.importer.baseUrl + '/api/document',
  form: qs.stringify(data)
}, function (error, response, body) {
  if (error || !response || response.statusCode !== 200) {
    spinner.fail('Upload failed for ' + file + ': ' + error);
    resolve();
fork icon0
star icon0
watch icon1

+ 3 other calls in file

58
59
60
61
62
63
64
65
66
67

const logoutURL = new URL(
  `https://${process.env.AUTH0_DOMAIN}/v2/logout`
);

const searchString = querystring.stringify({
  client_id: process.env.AUTH0_CLIENT_ID,
  returnTo: returnTo
});
logoutURL.search = searchString;
fork icon0
star icon0
watch icon1

+ 4 other calls in file