Last active
January 17, 2021 09:27
-
-
Save pgte/cd559940dd1ee1d81cc1 to your computer and use it in GitHub Desktop.
node request and response life cycle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var https = require('https'); | |
var querystring = require('querystring'); | |
var events = ['socket', 'connection', 'response', 'data', 'end', 'close', 'finish']; | |
var postData = querystring.stringify({ | |
'msg' : 'Hello World!' | |
}); | |
var options = { | |
hostname: 'www.google.com', | |
port: 443, | |
path: '/upload', | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Content-Length': postData.length | |
} | |
}; | |
var req = https.request(options, function(res) { | |
res.setEncoding('utf8'); | |
res.on('data', function (chunk) { | |
console.log('res data: %j', chunk.substring(0, 30) + '...'); | |
}); | |
observe('response', res); | |
}); | |
observe('request', req); | |
req.end(postData); | |
function observe(name, emitter) { | |
events.forEach(function(event) { | |
emitter.on(event, function() { | |
console.log('%s - %s', name, event); | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
request - socket | |
request - finish | |
request - response | |
res data: "<!DOCTYPE html>\n<html lang=en>..." | |
response - data | |
res data: ":url(//www.google.com/images/b..." | |
response - data | |
res data: "o_color_150x54dp.png) no-repea..." | |
response - data | |
response - end | |
request - close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment