我需要发出HTTP GET请求,但是在制作javascript对象的查询字符串时遇到了一些麻烦。这是我的对象。
var params = {
from: {
zip: '42100',
country: 'IT'
},
to: {
zip: '20019',
country: 'IT'
},
packages: [ { "width": 50, "height": 40, "length": 40, "weight": 2 } ]
};
我手动创建了查询字符串,这就是结果
from[zip]=42100&from[country]=IT&to[zip]=20019&to[country]=IT&packages[0]=[width]=50&[height]=40&[length]=40&[weight]=2
问题是Google说“您的客户发出了格式错误或非法的请求。”
这是我的NodeJS脚本。
var request = require('request');
var params = {
from: {
zip: '42100',
country: 'IT'
},
to: {
zip: '20019',
country: 'IT'
},
packages: [ { "width": 50, "height": 40, "length": 40, "weight": 2 } ]
};
function packagesToQueryString(packages) {
let stringa = "";
for (const onePackage of packages) {
stringa += '[width]='+ onePackage.width + '&[height]='+ onePackage.height +'&[length]='+ onePackage.length +'&[weight]='+ onePackage.weight +'';
}
return 'packages[' + (packages.length - 1) + ']=' + stringa;
}
function paramsToQueryString(obj) {
return 'from[zip]=' + obj.from.zip +'&from[country]=' + obj.from.country + '&to[zip]=' + obj.to.zip + '&to[country]=' + obj.to.country+ '&';
}
const formData = paramsToQueryString(params) + packagesToQueryString(params.packages);
console.log(formData);
request({
headers: {
'Authorization': 'fcd3dda8...2577',
'Content-Type': 'application/json'
},
body: formData,
uri: 'https://api.packlink.com/v1/services',
method: 'GET'
}, function (err, res, body) {
console.log(body);
});
答案 0 :(得分:1)
导致“格式错误或非法请求”错误的原因有两个:
Content-Type
被定义为application/json
。但是,body
的值为formData
(from[zip]=42100&from[country]=...
),它不是json。formData
,您的汇编逻辑也不正确。对于params
对象,其对应的查询字符串为:from%5Bzip%5D=42100&from%5Bcountry%5D=IT&to%5Bzip%5D=20019&to%5Bcountry%5D=IT&packages%5B0%5D%5Bwidth%5D=50&packages%5B0%5D%5Bheight%5D=40&packages%5B0%5D%5Blength%5D=40&packages%5B0%5D%5Bweight%5D=2
为了成功发送该HTTP GET请求,您需要使用qs
模块的request
选项。代码如下所示:
var request = require('request');
var params = {
from: {
zip: '42100',
country: 'IT'
},
to: {
zip: '20019',
country: 'IT'
},
packages: [ { "width": 50, "height": 40, "length": 40, "weight": 2 } ]
};
request({
headers: {
'Authorization': 'fcd3dda8...2577'
},
qs: params,
uri: 'https://api.packlink.com/v1/services',
method: 'GET'
}, function (err, res, body) {
console.log(body);
});