简体   繁体   English

node.js的Hello World示例中的函数参数

[英]Function arguments in node.js' Hello World example

I'm new to JavaScript and am trying to teach myself using code posted online. 我是JavaScript的新手,正在尝试使用在线发布的代码自学。 I'm unsure of the way arguments are passed into various functions at various levels. 我不确定参数在各个级别传递到各种函数的方式。

For instance, in the node.js "Hello World" example (reproduced below), where do the 'req' and 'res' variables come from and how does the client call the server and pass this information to it (and get the result) !?! 例如,在node.js“ Hello World”示例(如下所示)中,“ req”和“ res”变量来自何处,客户端如何调用服务器并将此信息传递给服务器(并获得结果) )!?!

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

It's just a function body that is passed to the createServer method. 它只是一个传递给createServer方法的函数体。 The variables req and res don't exist as they are not variables, they are the function parameters, and those names are commonly used for readability, but in no way are obligatory - for example, the code would work the same if you did: 变量reqres不存在,因为它们不是变量,它们是函数参数,并且这些名称通常用于提高可读性,但绝不是必须的-例如,如果您这样做,代码将工作相同:

http.createServer(function (a, b) {
  b.writeHead(200, {'Content-Type': 'text/plain'});
  b.end('Hello World\n');
}).listen(1337, '127.0.0.1');

You know, just like when you define a function: 您知道,就像定义函数时一样:

function someFunction(firstParam, secondParam) {
    // do something with firstParam and secondParam
}

But I'm not sure how a function with no name (anonymous) nested inside another function (or method) is called from somewhere else. 但是我不确定如何从其他地方调用嵌套在另一个函数(或方法)中的没有名称(匿名)的函数。

See if this helps you understand: 看看这是否有助于您理解:

 function add(a,b){return a+b} function sub(a,b){return ab} function math(f, x, y) { alert(f(x, y)); } math(add, 1, 2); math(sub, 8, 4); // pass in anon function - multiplication math(function(a, b){return a * b}, 2, 5); 

Req -> Http (https) Request Object. 请求-> Http(https)请求对象。 You can get the request query, params, body, headers and cookies from it. 您可以从中获取请求查询,参数,正文,标题和cookie。 You can overwrite any value or add anything there. 您可以覆盖任何值或在其中添加任何内容。 However, overwriting headers or cookies will not affect the output back to the browser. 但是,覆盖标头或cookie不会影响返回到浏览器的输出。

Res -> Http (https) Response Object. Res-> Http(https)响应对象。 The response back to the client browser. 响应返回到客户端浏览器。 You can put new cookies value and that will write to the client browser (under cross domain rules) Once you res.send() or res.redirect() or res.render(), you cannot do it again, otherwise, there will be uncaught error. 您可以放置​​新的cookie值,并将其写入客户端浏览器(在跨域规则下)。res.send()或res.redirect()或res.render()后,您将无法再执行此操作,否则,将未被发现的错误。

req = {
    _startTime     :    Date, 
    app            :    function(req,res){},
    body           :    {},
    client         :    Socket,
    complete       :    Boolean,
    connection     :    Socket,
    cookies        :     {},
    files          :     {},
    headers        :    {},
    httpVersion    :    String,
    httpVersionMajor    :    Number,
    httpVersionMinor    :     Number,
    method         :    String,  // e.g. GET POST PUT DELETE
    next           :    function next(err){},
    originalUrl    :    String,     /* e.g. /erer?param1=23¶m2=45 */
    params         :    [],
    query          :    {},
    readable       :    Boolean,
    res            :    ServerResponse,
    route          :    Route,
    signedCookies  :    {},
    socket         :    Socket,
    url            :    String /*e.g. /erer?param1=23¶m2=45 */
}

res = {
    app            :    function(req, res) {},
    chunkedEncoding:    Boolean,
    connection     :     Socket,
    finished       :    Boolean,
    output         :    [],
    outputEncodings:    [],
    req            :    IncomingMessage,
    sendDate       :    Boolean,
    shouldkeepAlive    : Boolean,
    socket         :     Socket,
    useChunkedEncdoingByDefault    :    Boolean,
    viewCallbacks  :    [],
    writable       :     Boolean
}

Have a look at the docs. 看一下文档。 They help: https://nodejs.org/api/http.html#http_http_createserver_requestlistener 他们帮助: https : //nodejs.org/api/http.html#http_http_createserver_requestlistener

http.createServer is creating an instance of http.Server. http.createServer正在创建http.Server的实例。 http.Server is an event emitter, which can emit several events, including "request." http.Server是事件发射器,它可以发射几个事件,包括“请求”。

The function you pass in as a parameter is the RequestListener. 您作为参数传递的函数是RequestListener。 The function you are passing in is the requestListener which is bound to the "request" event. 您传入的函数是绑定到“ request”事件的requestListener。

So you are creating an instance of http.Server, which emits events and calls functions in response to those events. 因此,您正在创建http.Server的实例,该实例发出事件并响应这些事件调用函数。 Suppose your instance of http.Server is http_server 假设您的http.Server实例是http_server

Underneath the hood, http_server probably does something like: 在引擎盖下,http_server可能会执行以下操作:

http_server.on('request', [yourFunction])

Node implicitly sends req and res into your function. Node隐式发送req和res到您的函数中。 So every time a client makes a request to your server, it emits the "request" event. 因此,每当客户端向您的服务器发出请求时,它都会发出“请求”事件。 Then since [yourFunction] is bound to the request event, it gets called with the req and res parameters passed in. 然后,由于[yourFunction]绑定到了请求事件,因此将使用传入的req和res参数来调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM