javascript对象的查询字符串

时间:2019-04-29 18:28:59

标签: node.js api http

我需要发出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);
});

Google error

1 个答案:

答案 0 :(得分:1)

导致“格式错误或非法请求”错误的原因有两个:

  1. 在您的HTTP请求中,Content-Type被定义为application/json。但是,body的值为formDatafrom[zip]=42100&from[country]=...),它不是json。
  2. 即使对于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);
});