简体   繁体   English

请求和响应来自哪里?

[英]Where are the request and response coming from?

On line 2, there are 'request' and 'response' parameters to be received, yet on line 6, in the createServer call, I pass it the request handler function, with no arguments. 在第2行,有“ request”和“ response”参数要接收,但是在第6行,在createServer调用中,我将不带参数的请求处理函数传递给它。 Where do these two specific parameters come from if I'm not passing them on invocation? 如果我没有在调用时传递它们,这两个特定参数从何而来?

var http = require("http");
function requestHandler(request, response) {
  console.log();
  response.end();
}
var server = http.createServer(requestHandler);
server.listen(3000);
// importing the http module
var http = require("http"); 

// defining what happens when a request hit the server (a.k.a callback function)
function requestHandler(request, response) {
  console.log();
  response.end();
}

// creating a server and linking the previously defined request handler.
var server = http.createServer(requestHandler);
server.listen(3000);

Since you have already defined what this handler takes in as params and what it does, you just need to provide the name of the function to link it to your newly created server. 由于您已经定义了该处理程序作为参数的用途以及它的作用,因此只需要提供函数名称即可将其链接到新创建的服务器。

In other words you are passing the function itself as a parameter to the createServer function. 换句话说,您要将函数本身作为参数传递给createServer函数。 Functions are first class in JavaScript. 函数是JavaScript中的第一类。

The params that you name in the request handler helps you read from the request and write to the response. 您在请求处理程序中命名的参数可以帮助您从请求中读取并写入响应。

The request and response parameters are coming from the script that will actually call your request handler. requestresponse参数来自实际上将调用您的请求处理程序的脚本。

The node server, when listening on the 3000 port, will catch requests, do some internal management on them (I assume, I don't exactly know what's going on down there), create a response object, and call your handler in a context that will allow it to return content. 节点服务器在侦听3000端口时,将捕获请求,对请求进行一些内部管理(我想,我不完全知道那里发生了什么),创建响应对象,并在上下文中调用处理程序这将允许它返回内容。


Here is a very simple unrelated synchronous exemple. 这是一个非常简单的不相关的同步示例。 When defining callback , we just define a function that will log whatever it is passed. 在定义callback ,我们仅定义一个函数,该函数将记录传递的所有信息。 That function is then passed to usesCallback , which will use it to accomplish the log. 然后usesCallback函数传递给usesCallback ,它将使用它来完成日志。

function callback(value) {
    console.log(value);
}
function getValue() {
    return 42;
}
function usesCallback(callback) {
    var value = getValue();
    callback(value);
}

usesCallback(callback);
// logs 42 to the console

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

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