Node.js - 在 HTTP GET 请求查询中发送时,数组被转换为对象 [英] Node.js - Array is converted to object when sent in HTTP GET request query
本文介绍了Node.js - 在 HTTP GET 请求查询中发送时,数组被转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下 Node.js 代码:
The following Node.js code:
var request = require('request');
var getLibs = function() {
var options = { packages: ['example1', 'example2', 'example3'], os: 'linux', pack_type: 'npm' }
request({url:'http://localhost:3000/package', qs:options},
function (error , response, body) {
if (! error && response.statusCode == 200) {
console.log(body);
} else if (error) {
console.log(error);
} else{
console.log(response.statusCode);
}
});
}();
发送以下 http GET 请求查询,该查询由如下方式接收:
sends the following http GET request query that is received by like this:
{"packages"=>{"0"=>"example1", "1"=>"example2", "2"=>"example3"}, "os"=>"linux", "pack_type"=>"npm"}
我如何优化此请求以接收这样的请求:
How can I optimize this request to be received like this:
{"packages"=>["example1", "example2", "example3"], "os"=>"linux", "pack_type"=>"npm"}
注意.REST API 是在 Ruby on Rails 中构建的
Note. The REST API is built in Ruby on Rails
推荐答案
我终于找到了解决办法.我使用 'qs' 用 {arrayFormat : 'brackets'} 将 'options' 字符串化,然后连接到以 '?' 结尾的 url如下:
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);
}
});
}();
注意:我尽量避免连接到 url,但所有响应的代码都是 400
Note: I tried to avoid concatenation to url, but all responses had code 400
这篇关于Node.js - 在 HTTP GET 请求查询中发送时,数组被转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文