I need to make a HTTP GET request but i have some trouble with making a querystring of a javascript object. This is my object.
var params = {
from: {
zip: '42100',
country: 'IT'
},
to: {
zip: '20019',
country: 'IT'
},
packages: [ { "width": 50, "height": 40, "length": 40, "weight": 2 } ]
};
I manually made my querystring and this is the result
from[zip]=42100&from[country]=IT&to[zip]=20019&to[country]=IT&packages[0]=[width]=50&[height]=40&[length]=40&[weight]=2
The problem is that Google says "Your client has issued a malformed or illegal request."
This is my NodeJS script.
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);
});