Reputation: 35
I am trying to send following Javascript object from one local nodejs (express) instance to another.
var v = {
items: [{
id: "fil1",
values: [
{ key: "123", timestamp: 333, value: "aaa" },
{ key: "123", timestamp: 333, value: "aaa" },
{ key: "123", timestamp: 333, value: "aaa" },
{ key: "123", timestamp: 333, value: "aaa" }
]
}]
};
I use the following post request where request = require('request')
, and params
is the JSON.stringified version of the object v
above.
var performPostRequest = function (ip, port, endpoint, params, callback) {
var url = "http://" + ip + ":" + port + "/" + endpoint;
request.post({
url: url,
form: params,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}, function (err, response, body) {
if (err) {
callback(err, body);
}
if (body) {
callback(err, JSON.parse(body));
}
});
};
The receiving endpoint looks like this:
router.post('/values', function (req, res) {
console.log(req.body);
res.status(201).send("");
});
Where router is express.Router().
So, to my question : When printing JSON.stringify(v)
at the sender, the result is a string matching the object v, but when printing the body of the request at the receiving endpoint, the string is messed up (see below). What am I doing wrong?
JSON.stringify(v)
on sender:
{"items":[{"id":"fil1","values":[{"key":"123","timestamp":333,"value":"aaa"},{"key":"123","timestamp":333,"value":"aaa"},{"key":"123","timestamp":333,"value":"aaa"},{"key":"123","timestamp":333,"value":"aaa"}]}]}
req.body
at receiver:
{ '{"items":': { '{"key":"123","timestamp":333,"value":"aaa"},{"key":"123","timestamp":333,"value":"aaa"},{"key":"123","timestamp":333,"value":"aaa"},{"key":"123","timestamp":333,"value":"aaa"}': '' } }
Upvotes: 1
Views: 177
Reputation: 45433
You can send JSON using request
using json
option that takes care of everything, from request doc :
json - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.
var request = require('request');
var options = {
url: url,
method: 'POST',
json: {
items: [{
id: "fil1",
values: [
{ key: "123", timestamp: 333, value: "aaa" },
{ key: "123", timestamp: 333, value: "aaa" },
{ key: "123", timestamp: 333, value: "aaa" },
{ key: "123", timestamp: 333, value: "aaa" }
]
}]
};
};
request(options, function(error, response, body) {
if (error) {
callback(err, body);
}
if (body) {
callback(error, body);
}
});
Upvotes: 1