【问题标题】:Node.js post request on http not finishinghttp上的Node.js发布请求未完成
【发布时间】:2016-05-15 13:05:03
【问题描述】:

在 node.js 中,我使用 http 请求模块发出此请求

var post_req = http.request({
    host: 'api.site1.ciscozeus.io',
    path: '/logs/' + ZUES_TOKEN + '/' + logName + '/',
    port: 80,
    method: 'POST',
    headers: {
        'Content-type' : 'application/x-www-form-urlencoded'
    }
}, function(res) {
    res.on('data', function (chunk) {
        console.log(1);
        cb(chunk);
    });
});
post_req.write(JSON.stringify({
    "logs" : JSON.stringify('[{"test":"value1"}]')
}));
post_req.on('error', function(e) {
    console.error(e);
});
post_req.end();

但我的问题是它似乎没有进入cb(chunk);。就像它不调用 end promise 函数一样。它不打印 console.log(1)。

该 api 有一个可以试用的测试站点,如果我在那里尝试,它就可以工作。以下是我在该工具中检查日志数据时的外观:

有谁知道我是否错误地附加了日志数据?我不想发布相同的数据。

谢谢

【问题讨论】:

  • 不需要对已经是字符串的东西调用 JSON.stringify()。您的请求可能格式不正确。听 res.on('err',...) 看看是否给你一个线索。

标签: node.js http


【解决方案1】:
post_req.write(JSON.stringify({
    "logs" : JSON.stringify('[{"test":"value1"}]')
}));

在上述代码部分中,内部JSON.stringify 不正确。你应该写'logs' : [{'test' : 'value1'}]。外部 JSON.stringify 将负责将整个 JSON object 转换为 string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2021-09-23
    相关资源
    最近更新 更多