I have this in my Node script (simplified for this question):
var http = require("http"),
url = require("url"),
options = url.parse("http://example.com/"),
moreOptions = url.parse("http://example.net/"),
callback,
request,
moreDifferentRequest;
callback = function( res ) {
console.log(res.socket._httpMessage._headers.host);
}
request = http.request( options, callback );
request.end();
moreDifferentRequest = http.request( moreDifferentOptions, callback );
moreDifferentRequest.end();
I'm grabbing the hostname from res.socket._httpMessage._headers.host
because it does not exist in res.headers
.
But the underscores give me pause. They say to me, "Hey, this is to be treated like a private property for internal use only by socket
, so don't read it, because it might totally get changed around in a later version and we're not going to tell you."
If I am right to think that I'm Doing It Wrong here, what is the correct way to get the hostname inside the callback? Or am I just totally misinterpreting the underscores and what I'm doing is fine?
Yes, that's exactly what they are trying to say. The right way would of course be public, documented APIs if that's possible. But if it's not possible, then you must do this and realize it's on you if something breaks.
Since you are sending the request, you can get the host header from:
options.host
HTTP responses don't have a host header, it's the client (you) that sends the host header in a request.
With wrapper function:
var http = require("http"),
opts = require("url").parse( "http://stackoverflow.com" );
function wrapper( options, callback ) {
return function() {
args = [].slice.call(arguments);
args.push( options );
return callback.apply( this, args );
}
}
request = http.request( opts, wrapper(opts, function(response, options){
console.log( options.host );
}));
request.end();