97

我正在尝试使用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。但是我得到了一个错误(400 undefined),而不是正确的 JSON 响应。

当我使用 CURL 使用相同的 JSON 和 API 密钥发出请求时,它工作正常。所以我的 API 密钥或 JSON 没有任何问题。

我的代码有什么问题?

编辑

工作卷曲示例:

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] QPX Express API 返回 400 解析错误

4

9 回答 9

173

我认为以下应该有效:

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

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

于 2014-11-28T14:25:10.970 回答
20

我在这方面工作了太久。帮助我的答案是: 发送 Content-Type: application/json post with node.js

它使用以下格式:

request({
    url: url,
    method: "POST",
    headers: {
        "content-type": "application/json",
        },
    json: requestData
//  body: JSON.stringify(requestData)
    }, function (error, resp, body) { ...
于 2015-04-27T19:55:19.557 回答
10

你不想要多部分,而是一个“普通”的 POST 请求(带有Content-Type: application/json)。这就是你所需要的:

var request = require('request');

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
  }
};

request('https://www.googleapis.com/qpxExpress/v1/trips/search?key=myApiKey',
        { json: true, body: requestData },
        function(err, res, body) {
  // `body` is a js object if request was successful
});
于 2014-11-28T14:26:48.153 回答
9

现在有了新的 JavaScript 版本(ECMAScript 6 http://es6-features.org/#ClassDefinition),有一种更好的方式来使用 nodejs 和 Promise 请求提交请求(http://www.wintellect.com/devcenter/nstieglitz/5 -伟大的功能在 es6-harmony

使用库: https ://github.com/request/request-promise

npm install --save request
npm install --save request-promise

客户:

//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');

rp({
    method: 'POST',
    uri: 'http://localhost:3000/',
    body: {
        val1 : 1,
        val2 : 2
    },
    json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
        console.log(parsedBody);
        // POST succeeded...
    })
    .catch(function (err) {
        console.log(parsedBody);
        // POST failed...
    });

服务器:

var express = require('express')
    , bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
    console.log(request.body);      // your JSON

    var jsonRequest = request.body;
    var jsonResponse = {};

    jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;

    response.send(jsonResponse);
});


app.listen(3000);
于 2017-05-17T13:33:55.823 回答
3

例子。

var request = require('request');

var url = "http://localhost:3000";

var requestData = {
    ...
} 

var data = {
    url: url,
    json: true,
    body: JSON.stringify(requestData)
}

request.post(data, function(error, httpResponse, body){
    console.log(body);
});

作为插入json: true选项,将正文设置为值的 JSON 表示并添加"Content-type": "application/json"标题。此外,将响应正文解析为 JSON。 关联

于 2018-01-25T12:53:06.037 回答
2

根据文档: https ://github.com/request/request

例子是:

  multipart: {
      chunked: false,
      data: [
        {
          'content-type': 'application/json', 
          body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
        },
      ]
    }

我想你发送一个需要字符串的对象,替换

body: requestData

经过

body: JSON.stringify(requestData)
于 2014-11-28T14:20:51.667 回答
2
       var request = require('request');
        request({
            url: "http://localhost:8001/xyz",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(requestData)
        }, function(error, response, body) {
            console.log(response);
        });
于 2017-03-24T10:14:42.270 回答
0

我觉得

var x = request.post({
       uri: config.uri,
       json: reqData
    });

像这样定义将是编写代码的有效方式。并且 application/json 应该被自动添加。无需特别声明。

于 2018-01-10T06:16:36.283 回答
0

您可以将 json 对象作为获取请求的主体(第三个参数)传递。

于 2020-01-15T04:32:15.597 回答