在post请求期间更改了JSON字符串

时间:2017-02-24 22:38:49

标签: javascript json node.js

我正在尝试将以下Javascript对象从一个本地nodejs(express)实例发送到另一个。

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" }
        ]
    }]
};

我使用以下帖子请求,其中request = require('request')params是上面对象v的JSON.stringified版本。

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));
    }
});
};

接收端点如下所示:

router.post('/values', function (req, res) {

    console.log(req.body);

    res.status(201).send("");
});

路由器是express.Router()。

所以,对于我的问题:在发件人处打印JSON.stringify(v)时,结果是与对象v匹配的字符串,但是当在接收端点处打印请求正文时,字符串被弄乱起来(见下文)。我做错了什么?

发件人

JSON.stringify(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"}]}]}
收件人

req.body

{ '{"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"}': '' } }

1 个答案:

答案 0 :(得分:1)

您可以使用json使用request选项发送JSON来处理所有内容,request doc

  

json - 将body设置为值的JSON表示并添加   内容类型:application / json标头。另外,解析   响应机构为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);
    }
});