node.js 将 JSON 传递给 HTTP POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27190447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pass JSON to HTTP POST Request
提问by Ronin
I'm trying to make a HTTP POST request to the google QPX Express API [1] using nodejsand request[2].
我正在尝试使用nodejs和请求[2]向 google QPX Express API [1] 发出 HTTP POST 请求。
My code looks as follows:
我的代码如下所示:
// 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)
}
})
What I'm trying to do is passing the JSON using the multipart argument [3]. But instead of the proper JSON response I got an error (400 undefined).
我想要做的是使用 multipart 参数 [3] 传递 JSON。但是我得到了一个错误(400 未定义),而不是正确的 JSON 响应。
When I make a request using the same JSON and API Key using CURL instead, it works fine. So there's nothing wrong with my API key or JSON.
当我使用相同的 JSON 和 API Key 使用 CURL 发出请求时,它工作正常。所以我的 API 密钥或 JSON 没有任何问题。
What's wrong with my code?
我的代码有什么问题?
EDIT:
编辑:
working CURL example:
工作 CURL 示例:
i) I saved the JSON which I would pass to my request into a file called "request.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) then, in the terminal I switched to the directory in which the newly created request.json file was located and run (myApiKey stands for my actual API Key obviously):
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] a http request client designed for nodejs: https://www.npmjs.org/package/request[3] here is an example I found https://www.npmjs.org/package/request#multipart-related[4] QPX Express API is returning 400 parse error
[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 解析错误
回答by Tobi
I think the following should work:
我认为以下应该有效:
// fire request
request({
url: url,
method: "POST",
json: requestData
}, ...
In this case, the Content-type: application/jsonheader is automatically added.
在这种情况下,Content-type: application/json会自动添加标题。
回答by DanBaker
I worked on this for too long. The answer that helped me was at: send Content-Type: application/json post with node.js
我在这方面工作了太久。帮助我的答案是: 使用 node.js 发送 Content-Type: application/json post
Which uses the following format:
其中使用以下格式:
request({
url: url,
method: "POST",
headers: {
"content-type": "application/json",
},
json: requestData
// body: JSON.stringify(requestData)
}, function (error, resp, body) { ...
回答by mscdex
You don't want multipart, but a "plain" POST request (with Content-Type: application/json) instead. Here is all you need:
您不需要多部分,而是需要“普通” 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
});
回答by Evalds Urtans
Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)
现在有了新的 JavaScript 版本(ECMAScript 6 http://es6-features.org/#ClassDefinition),有一种更好的方式来使用 nodejs 和 Promise 请求提交请求(http://www.wintellect.com/devcenter/nstieglitz/5 -great-features-in-es6-harmony)
Using library: https://github.com/request/request-promise
使用库:https: //github.com/request/request-promise
npm install --save request
npm install --save request-promise
client:
客户:
//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...
});
server:
服务器:
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);
回答by Ashish Gupta
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);
});
回答by Baart
According to doc: https://github.com/request/request
根据文档:https: //github.com/request/request
The example is:
例子是:
multipart: {
chunked: false,
data: [
{
'content-type': 'application/json',
body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
},
]
}
I think you send an object where a string is expected, replace
我认为你发送了一个需要字符串的对象,替换
body: requestData
by
经过
body: JSON.stringify(requestData)
回答by Youngmin Kim
Example.
例子。
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);
});
As inserting json: trueoption,
sets body to JSON representation of value and adds "Content-type": "application/json"header. Additionally, parses the response body as JSON.
LINK
作为插入json: true选项,将正文设置为值的 JSON 表示并添加"Content-type": "application/json"标头。此外,将响应正文解析为 JSON。
关联
回答by ankur tiwari
you can pass the json object as the body(third argument) of the fetch request.
您可以将 json 对象作为获取请求的主体(第三个参数)传递。
回答by Siddhartha Thota
I feel
我觉得
var x = request.post({
uri: config.uri,
json: reqData
});
Defining like this will be the effective way of writing your code. And application/json should be automatically added. There is no need to specifically declare it.
像这样定义将是编写代码的有效方式。并且应该自动添加 application/json。无需特别声明。

