HTTP请求回调没有执行 - 为什么?

时间:2016-08-04 15:23:59

标签: javascript node.js http callback

我尝试向第三方API提交HTTP POST请求。它目前包含在promise方法中。

回调函数永远不会执行,但是当我单独运行下面的代码时,对API的调用是成功的。

我对Node.js和事件循环的想法相当新。幕后究竟发生了什么以及为什么回调函数不能执行?

代码:

// SQL Query successfully called and passed into done() function
.done(function(sqlResult) {

// contact already exists. resolve the issue
if(sqlResult[0]) {
    deferred.resolve("Contact already exists in database.");
}

// no contact found. create new HubSpot contact
else {
    console.log("No contact found. Creating HubSpot contact...");

    // create the POST data object
    var postData = querystring.stringify({
        'email': contact.email,
        'firstname': contact.first_name,
        'lastname': contact.last_name,
        'hs_context': JSON.stringify({
            'hutk': contact.cookie,
            'ipAddress': hs_context.ipAddress,
            'pageUrl': hs_context.pageUrl,
            'pageName': hs_context.pageName
        })
    }),

    // set POST options
    options = {
        hostname: 'forms.hubspot.com',
        path: '/uploads/form/v2/xxxxxx/' + formID,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': postData.length
        }
    };

    // set up request
    console.log("Setting up HubSpot API request.");
    var request = http.request(options, function(response) {
        // THIS CALLBACK DOES NOT EXECUTE
        console.log("TEST - INSIDE REQUEST CALLBACK.");
        console.log("Status: " + response.statusCode);
        console.log("Headers: " + JSON.stringify(response.headers));
        response.setEncoding('utf8');
        response.on('data', function(chunk) {
            console.log("Body: " + chunk);
        });
    });

    // handle any errors
    request.on('error', function(e) {
        console.log("Problem with request - " + e);
    });

    // Post the data
    console.log("Posting data.");
    request.write(postData);
    request.end();
} // end of else 

...

输出:

No contact found. Creating HubSpot contact...
Setting up HubSpot API request.
Posting data.

有什么建议吗?我收到了Hubspot的API文档中的代码 - http://developers.hubspot.com/docs/methods/forms/submit_form - 并进行了调整以满足我的需求。

更新

我注意到我的几个测试成功进行了API调用。 console.log()都没有显示,但是当我转到第三方网站时,我会立即看到API调用已成功完成。

我在测试时做了一个快速的时间戳。

12:09:12 - Unsuccessful
12:10:45 - Unsuccessful
12:11:05 - Unsuccessful
12:11:14 - Unsuccessful
12:11:32 - Successful!

我仍然在努力了解这种情况会如何发生......

1 个答案:

答案 0 :(得分:0)

我没有提到我正在使用Mocha进行测试。测试代码没有包含describe/it,因此代码将在收到任何响应之前完成执行。我将测试代码更改为以下内容:

describe("Submitting form to HubSpot API", function() {
    it("should return 204 status code", function(done) {
        test.createContact(contact, context, formID)
        .done(function(response) {
            test.log("CreateContact resolved! SUCCESS: " + response);
        })
        .fail(function(response) {
            test.log("CreateContact rejected! ERROR: " + response);
        })
        .always(function() {
            done();
        });
    });
});

我终于收到了回复!