小编典典

将JSON传递到HTTP POST请求

node.js

我正在尝试使用 nodejs 请求 [2] 向google QPX Express API [1]发出HTTP
POST请求。

我的代码如下:

    // create http request client to consume the QPX API
    var request = require("request")

    // JSON to be passed to the QPX Express API
    var requestData = {
        "request": {
            "slice": [
                {
                    "origin": "ZRH",
                    "destination": "DUS",
                    "date": "2014-12-02"
                }
            ],
            "passengers": {
                "adultCount": 1,
                "infantInLapCount": 0,
                "infantInSeatCount": 0,
                "childCount": 0,
                "seniorCount": 0
            },
            "solutions": 2,
            "refundable": false
        }
    }

    // QPX REST API URL (I censored my api key)
    url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=myApiKey"

    // fire request
    request({
        url: url,
        json: true,
        multipart: {
            chunked: false,
            data: [
                {
                    'content-type': 'application/json',
                    body: requestData
                }
            ]
        }
    }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            console.log(body)
        }
        else {

            console.log("error: " + error)
            console.log("response.statusCode: " + response.statusCode)
            console.log("response.statusText: " + response.statusText)
        }
    })

我想做的是使用multipart参数[3]传递JSON。但是我没有正确的JSON响应,而是收到一个错误(未定义400)。

当我使用CURL使用相同的JSON和API密钥发出请求时,它工作正常。因此,我的API密钥或JSON没错。

我的代码有什么问题?

编辑

工作的CURL示例:

i)我将传递给我的请求的JSON保存到名为“ request.json”的文件中:

{
  "request": {
    "slice": [
      {
        "origin": "ZRH",
        "destination": "DUS",
        "date": "2014-12-02"
      }
    ],
    "passengers": {
      "adultCount": 1,
      "infantInLapCount": 0,
      "infantInSeatCount": 0,
      "childCount": 0,
      "seniorCount": 0
    },
    "solutions": 20,
    "refundable": false
  }
}

ii)然后,在终端中,我切换到新创建的request.json文件所在的目录并运行(myApiKey显然代表我的实际API密钥):

curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=myApiKey

[1] https://developers.google.com/qpx-
express/
[2]专为nodejs设计的http请求客户端:https
://www.npmjs.org/package/request
[3]这是我发现的示例https://www.npmjs.org/package/request#multipart-
related [4]


阅读 270

收藏
2020-07-07

共1个答案

小编典典

我认为以下应该起作用:

// fire request
request({
    url: url,
    method: "POST",
    json: requestData
}, ...

在这种情况下,Content-type: application/json标题将自动添加。

2020-07-07