尝试从node.js执行POST请求时获取400请求TimeOut错误

时间:2017-08-23 05:37:05

标签: javascript jquery node.js

以下是详细解释

我已设置发布数据

var post_data = JSON.stringify({
    "primaryContact": {
        "id": 'contact_id'
    },
    "subject": "subject"
});

设置https模块选项

var https_options_post = {
    host: hostName,
    method: 'POST',
    path: "/services/rest/connect/v1.3/incidents",
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(post_data),
        'Authorization': auth
    }
}

创建了一个处理POST请求的函数

function postJSON(https_options_post, callback) {
    var request = https.request(https_options_post, function (response) {
        console.log('In POST Request Function block');
        var body = '';
        response.on('data', function (chunk) {
            body += chunk;
        });
        response.on('end', function () {
            console.log(body);
            var bodyJSON = JSON.parse(body);
            var result = "Incident Reference Number: " + bodyJSON.lookupName;
            callback(null, result);
        });
        response.on('error', callback);
    })
    .on('error', callback)
    .end();

调用函数

postJSON(https_options_post, function (err, result) {
  if (err) {
    return console.log('Error while retrieving Data: ', err);
  }
    console.log(result);
});

但返回的回复是

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
  <head>
    <title>408 Request Time-out</title>
  </head>
  <body>
    <h1>Request Time-out</h1>
    <p>Server timeout waiting for the HTTP request from the client.</p>
  </body>
</html>

当我使用REST客户端扩展命中chrome中的API并传递基本auth参数时,服务器返回的是JSON。请帮忙告诉代码中是否有错误。

2 个答案:

答案 0 :(得分:1)

没有数据写入request流,服务器会保留Content-Length个字节的数据。在request.write(post_data)解决之前写request.end()

答案 1 :(得分:0)

与Node.js融合示例参考:

reqGet.write(jsonObject)
reqGet.end();
reqGet.on('error', function(e) {
    console.error(e);
});

代码复制了Ref和完整示例, https://www.snippetbucket.com/confluence-nodejs-rest-api/