Ответ 1
Я думаю, что следующее должно работать:
// fire request
request({
url: url,
method: "POST",
json: requestData
}, ...
В этом случае заголовок Content-type: application/json
автоматически добавляется.
Я пытаюсь выполнить запрос HTTP POST в API QIP X Express Express [1], используя nodejs и запрос [2].
Мой код выглядит следующим образом:
// 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)
}
})
То, что я пытаюсь сделать, это передать JSON с помощью аргумента multipart [3]. Но вместо правильного ответа JSON я получил ошибку (400 undefined).
Когда я делаю запрос, используя тот же JSON и API-ключ, используя CURL, он работает нормально. Так что ничего не случилось с моим 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] клиент запросов http, предназначенный для nodejs: https://www.npmjs.org/package/request [3] вот пример, который я нашел https://www.npmjs.org/package/request#multipart-related [4] QPX Express API возвращает 400 ошибок синтаксического анализа
Я думаю, что следующее должно работать:
// fire request
request({
url: url,
method: "POST",
json: requestData
}, ...
В этом случае заголовок Content-type: application/json
автоматически добавляется.
Я работал над этим слишком долго. Ответ, который мне помог, был: отправить Content-Type: application/json post с node.js
Используется следующий формат:
request({
url: url,
method: "POST",
headers: {
"content-type": "application/json",
},
json: requestData
// body: JSON.stringify(requestData)
}, function (error, resp, body) { ...
Вы не хотите использовать множественный, но простой запрос 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
});
Теперь с новой версией JavaScript (ECMAScript 6 http://es6-features.org/#ClassDefinition) есть лучший способ отправки запросов с помощью nodejs и запроса Promise (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-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);
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);
});
Согласно документу: 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)