I\'m trying to make a HTTP POST request to the google QPX Express API [1] using nodejs and request [2].
My code l
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.
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.
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
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);