nodejs中的服务器地址和端口,并使用http.createServer表示
新节点和快递。需要知道如何获取服务器IP和端口。试了几件事:
const express = require('express');
const app = express();
var http = require('http');
app.set('port',12346);
var httpServer = http.createServer(app).listen(app.get('port'));
function getMethod(req,res) {
console.log("Server Port is: "+ app.get('port'));
// console.log("Server Port is: "+ httpServer.address);
console.log("Connection Type: "+ req.protocol);
res.send("Hello world!");
}
app.get('/', getMethod);
在上面的代码app.get返回我的服务器端口,但如果我查询httpServer.address它返回undefined和app.address()。端口返回错误。 有没有办法在没有在应用程序中设置它的情况下获得它?
回答如下:http.Server
's listen
是异步的,你不应该在address()
事件发送之前调用listening
(来自docs Don't call server.address() until the 'listening' event has been emitted.
)。
您可以通过几种方式执行此操作,订阅listening
回调:
httpServer.on('listening', function () {
console.log(app.address().port)
})
或者只是使用app.listen
(创建一个http.Server
)并检查listen
接受的回调中的实例端口:
let appInstance = app.listen(1337, function () {
console.log(`'Server listening at: ${appInstance.address().port}`)
})
这消除了require
http
模块的需要,并在一定程度上简化了代码。
set
上的get
/ app
方法允许您在快速应用程序上设置和检索任意值。其中一些值是“特殊的”(参见docs)并影响应用程序的行为,但没有什么能阻止你设置像port
这样的属性;问题在于它实际上不会改变应用程序监听的port
。