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

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

The following Node.js code:

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

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


        
3条回答
  •  旧时难觅i
    2021-01-27 21:58

    I finally found a fix. I used 'qs' to stringify 'options' with {arrayFormat : 'brackets'} and then concatinated to url ended with '?' as follows:

    var request = require('request');
    var qs1 = require('qs');
    
    var getLibs = function() {
        var options = qs1.stringify({ 
            packages: ['example1', 'example2', 'example3'], 
            os: 'linux', 
            pack_type: 'npm' 
            },{
            arrayFormat : 'brackets'
        });
    
    
        request({url:'http://localhost:3000/package?' + options}, 
        function (error , response, body) {
            if (! error && response.statusCode == 200) {
                console.log(body);
            } else if (error) {
                console.log(error);
            } else{
                console.log(response.statusCode);
            }
        });
    }();
    

    Note: I tried to avoid concatenation to url, but all responses had code 400

提交回复
热议问题