调试错误请求400错误

时间:2016-11-02 12:14:06

标签: javascript json express request http-post

我正在尝试从Google的QPX Express API返回一个航班列表,不过我对一个错误的请求回复感到难过:

{ StatusCodeError: 400 - {"error":{"errors":[{"domain":"global","reason":"badRequest","message":"Invalid inputs: received empty request."}],"code":400,"message":"Invalid inputs: received empty request."}}

我是如何接近请求结构的?我正在使用request-promise

const options = {
  method: 'POST',
  uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXX',

  qs: {
   "request": {
     "passengers": {
       "adultCount": 1 },
       "slice": [{"origin": "BOS",
                  "destination": "LAX",
                  "date": "2017-03-01"
                }]
              }
        },
    json: true
}

request(options)
  .then(function (response) {
    console.log(response)
  })
  .catch(function (err) {
    console.log(err)
  })

2 个答案:

答案 0 :(得分:0)

检查:

const options = {
  method: 'POST',
  uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXX',

  qs: {
   "request": {
     "passengers": {
       "adultCount": 1 },
       "slice": [{"origin": "BOS",
                  "destination": "LAX",
                  "date": "2017-03-01"
                }]
              }
        },
    json: true
};

request(options)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  });

你忘了结束uri字符串。另外请不要忘记分号。

编辑: 尝试:

request({
    url: (your url here),
    method: "POST",
    json: requestData
},

其中requestData将是你的qs。

答案 1 :(得分:0)

我已经解决了这个问题。该请求需要将数据包含在body密钥中,并且内容类型设置为JSON。

现在可以按预期从API返回数据。

const options = {
  method: 'POST',
  uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?&key=XXXXXXXXXXXXXXXXXXXX',
  body: {
  "request": {
    "passengers": {
      "adultCount": "1"
    },
    "slice": [
      {
        "origin": "SFO",
        "destination": "LAX",
        "date": "2017-06-19"
      }
    ],
    "solutions": "1"
  }
},
  json: true
}

request(options)
  .then(function (response) {
    console.log(response.trips.tripOption[0].saleTotal)
  })
  .catch(function (err) {
    console.log(err)
  })