Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
(Javascript)为什么';t函数取参数_Javascript_Node.js - Fatal编程技术网

(Javascript)为什么';t函数取参数

(Javascript)为什么';t函数取参数,javascript,node.js,Javascript,Node.js,这是一个NodeJS的东西,代码是: var http = require("http"); function onRequest(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); 我的问题是

这是一个NodeJS的东西,代码是:

var http = require("http");

function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888);

我的问题是,为什么在最后一行中,onRequest函数不接受参数。。我是Javascript新手,但onRequest不应该接受函数中定义的2个参数吗?有人能帮我吗?我被困了一个小时:(

您实际上并没有调用该方法。您正在告诉
createServer
它的
requestListener
回调函数是什么

从node.js文档()中:

http.createServer([requestListener])

返回一个新的web服务器对象

requestListener是一个自动添加到 “请求”事件


onRequest函数的执行需要2个参数

您的最后一行:

http.createServer(onRequest).listen(8888);
实际上不执行onRequest,尽管我可以理解为什么您会这么认为。它将对onRequest函数的引用传递给http.createServer函数/方法

createServer将保存一个指向onRequest函数的指针,然后当请求进入服务器时,它将执行onRequest。该执行将包括一个请求和响应参数

关于详细信息,本文对这种模式(称为回调)给出了一个相当直接和简洁的解释。它通常与异步编程一起使用,但不一定非得如此


onRequest有两个参数,请求和响应。createServer有一个参数,即事件函数。函数是对象。
onRequest
是函数对象。
onRequest()
调用函数
onRequest
并返回其值。@john,有什么答案有用吗?是的,谢谢:D Brandon