Node.js - Array is converted to object when sent in HTTP GET request query

后端 未结 3 1854
情书的邮戳
情书的邮戳 2021-01-27 21:10

The following Node.js code:

var request = require(\'request\');

var getLibs = function() {
    var options = { packages: [\'example1\', \'example2\', \'example3         


        
3条回答
  •  故里飘歌
    2021-01-27 21:34

    If the array need to be received as it is, you can set useQuerystring as true:

    UPDATE: list key in the following code example has been changed to 'list[]', so that OP's ruby backend can successfully parse the array.

    Here is example code:

    const request = require('request');
    
    let data = {
      'name': 'John',
      'list[]': ['XXX', 'YYY', 'ZZZ']
    };
    
    request({
      url: 'https://requestb.in/1fg1v0i1',
      qs: data,
      useQuerystring: true
    }, function(err, res, body) {
      // ...
    });
    

    In this way, when the HTTP GET request is sent, the query parameters would be:

    ?name=John&list[]=XXX&list[]=YYY&list[]=ZZZ
    

    and the list field would be parsed as ['XXX', 'YYY', 'ZZZ']


    Without useQuerystring (default value as false), the query parameters would be:

    ?name=John&list[][0]=XXX&list[][1]=YYY&list[][2]=ZZZ
    

提交回复
热议问题