如何使用正确的请求和响应对象调用函数?

蝙蝠侠

我有一段代码:

var http = require('http');
function createApplication() {
    let app = function(req,res,next) {
        console.log("hello")
    };

    return app;
}

app = createApplication();

app.listen = function listen() {
    var server = http.createServer(this);
    return server.listen.apply(server, arguments);
};

app.listen(3000, () => console.log('Example app listening on port 3000!'))

这里没什么好看的。但是当我运行此代码并转到 时localhost:3000,我可以看到hello正在打印。我完全不确定这个函数是如何被调用的。此外,该函数也接收req&res对象。不确定这里发生了什么。

帕特里克·埃文斯

http.createServer()有几个可选参数。一个requestListener

https://nodejs.org/api/http.html#http_http_createserver_options_requestlistener

requestListener 是一个自动添加到“请求”事件的函数。

既然你打电话给你listen(),像这样app.listen()this内部的功能将是向你作出的,并在返回的函数的引用createApplication所以你基本上是在做:

http.createServer(function(req,res,next) {
  console.log("hello")
});

因此,您的函数被添加为任何请求的回调,因此为什么您发出的任何请求都会创建hello的控制台日志

如果你想要一个等效的更直接的例子

var http = require('http');
var server = http.createServer();
server.on('request',function(req,res,next) {
  //callback anytime a request is made
  console.log("hello")
});
server.listen(3000);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章