サードパーティAPIにHTTP POSTリクエストを送信しようとしています。現在、約束の方法で包まれています。HTTPリクエストコールバックが実行されていません - なぜですか?
コールバック関数は実行されませんが、以下のコードを単独で実行すると、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!
私はまだ、私はテストのためにモカを使用しています言及することができなかった...これが起こることができる方法を理解するために
このコールバックは非同期的に発生するため、 'request.write()'がコールバックを正しく起動して実行する前に、 'request.write()'が要求をうんざりさせている可能性があります。 – EnKrypt
@EnKrypt - これが当てはまるとします。 'request.write()'と 'request.end()'の間に実行する他のコードはありません。何か提案はありますか? – sincity
リクエストを設定して送信する方法に問題はないようです。 APIがあなたのリクエストに応答していると確信していますか?多分何かが間違っているのでしょうか? 'req.on( 'error'、function(e){console.log(e)})'で 'error'イベントを聞いてみてください。 –