本文介绍了使用以下划线("_")开头的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Node脚本中有此名称(针对此问题进行了简化):

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();

我正在从 res.socket._httpMessage._headers.host 中获取主机名,因为它在 res.headers 中不存在.

I'm grabbing the hostname from res.socket._httpMessage._headers.host because it does not exist in res.headers.

但是下划线让我停下来.他们对我说:嘿,这只能作为 socket 内部使用的私有财产,所以请不要阅读它,因为它可能在以后的版本中完全被改变,并且我们不会告诉你."

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?

推荐答案

是的,这正是他们要说的.如果可能的话,正确的方法当然是公开的,有文档证明的API.但是,如果不可能,那么您必须执行此操作,并意识到如果出现故障,它就在您身上.

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响应没有主机头,是客户端(您)在请求中发送主机头.

HTTP responses don't have a host header, it's the client (you) that sends the host header in a request.

具有包装器功能:

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();

这篇关于使用以下划线("_")开头的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:40