javascript - 如何使用正确的请求和响应对象调用函数?
问题描述
我有一段代码:
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);
推荐阅读
- ios - 如何通过命令行在真实 iOS 设备上打开 iOS 应用程序的深层链接?
- python - 如何更改 tf.keras 以使 _Merge 类公开可用?
- android - 小球原生组件显示当前页面
- python - 如何在 requirements.txt 中添加 git 源
- aws-alb - 我们可以重命名 AWSALB cookie 吗?
- dialogflow-es - 如果没有响应,则在移动设备上重新提示用户
- java - ObjectMapper 通过 API Gateway 破坏 AWS Lambda
- gitlab - 如何添加本地 git 项目并将其推送到远程分支
- angular - Kubernetes 上的 Angular(入口路由)
- java - 我应该使用静态绑定吗?