首页 > 解决方案 > 如何使用正确的请求和响应对象调用函数?

问题描述

我有一段代码:

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对象。不知道这里发生了什么。

标签: javascriptnode.js

解决方案


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

推荐阅读