node.js - 为什么我们在 http.createServer(app) 中传递“app”
问题描述
为什么我们在 http.createServer(app) 中传递“app”,因为我们也可以传递
例如:
var app = require('./app')
const http = require('http')
const port = 3500 || process.env.PORT
var server = http.createServer(app) //here we pass app
在其他代码中,我们传递了一些不同的参数,例如
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(port)
解决方案
在您的第一个示例中,我假设它app
代表一个 Express 实例,如下所示:
const app = express();
如果是这样,那么app
是一个也具有属性的请求处理函数。你可以像这样传递它:
var server = http.createServer(app);
因为该app
函数专门设计为一个 http 请求侦听器,它从传入的 http 请求传递参数,如您在 doc(req, res)
中所见。
或者,在 Express 中,您还可以执行以下操作:
const server = app.listen(80);
在这种情况下,它会http.createServer(app)
为您执行此操作,然后还会调用server.listen(port)
并返回新的服务器实例。
当你这样做时:
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(port);
您只是在创建自己的函数来处理传入的 http 请求,而不是使用 Express 库为您创建的函数。
推荐阅读
- java - Maven 资源插件:过滤时删除反斜杠
- c# - C# WebApi - 在 HTTPRequest 中发送长文本不起作用
- csv - 使用 SAVE TRANSLATE 导出为 CSV,但空值导出为单个空格
- machine-learning - Pyspark 训练的 Logistic 回归模型没有 predict() 和 predictProbability() 函数
- julia - Julia 宏观卫生的载体
- opendaylight - 由于 ietf-netconf@2011-06-01.yang 版本不兼容,ietf-netconf 操作失败,我们如何使其工作?
- java - 在 java 中创建子数组是否使用 O(1) 额外空间
- python - 雪花截断被回滚
- tensorflow - 将 BERT pytorch 模型转换为 TF 检查点
- jpa - 如何根据作为另一个属性的 id 指定 JPA ManyToOne 关系