HTTP POST 요청에 JSON 전달
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] 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
I think the following should work:
// fire request
request({
url: url,
method: "POST",
json: requestData
}, ...
In this case, the Content-type: application/json
header is automatically added.
I worked on this for too long. The answer that helped me was at: send Content-Type: application/json post with node.js
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) { ...
You don't want multipart, but a "plain" POST request (with Content-Type: application/json
) instead. Here is all you need:
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
});
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)
Using library: 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);
According to doc: 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)
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);
});
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: true
option, sets body to JSON representation of value and adds "Content-type": "application/json"
header. Additionally, parses the response body as JSON. LINK
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.
참고URL : https://stackoverflow.com/questions/27190447/pass-json-to-http-post-request
'program story' 카테고리의 다른 글
DIV를 하단 또는 기준선에 정렬 (0) | 2020.09.18 |
---|---|
파이썬에서 사전을 어떻게 병합합니까? (0) | 2020.09.18 |
Clang으로 C ++를 어떻게 컴파일합니까? (0) | 2020.09.18 |
OSX의 명령 줄에서 GUI Emacs를 시작하는 방법은 무엇입니까? (0) | 2020.09.18 |
Rails Admin vs. ActiveAdmin (0) | 2020.09.17 |