NodeJS:如何获取服务器的端口?

2020/11/14 12:22 · javascript ·  · 0评论

您经常会看到Node的示例hello world代码,该代码创建Http Server,开始侦听端口,然后执行以下操作:

console.log('Server is listening on port 8000');

但理想情况下,您希望这样做:

console.log('Server is listening on port ' + server.port);

我如何检索服务器当前正在侦听的端口,而不在调用之前将数字存储在变量中server.listen()

我之前已经看过这件事,但是在Node文档中找不到。也许这是表达的特定内容?

Express 4.x答案:

Express 4.x(根据下面的Tien Do回答)现在将app.listen()视为异步操作,因此listener.address()将仅在app.listen()的回调内部返回数据:

var app = require('express')();

var listener = app.listen(8888, function(){
    console.log('Listening on port ' + listener.address().port); //Listening on port 8888
});

快递3答案:

我认为您正在寻找这个(特定于表达?):

console.log("Express server listening on port %d", app.address().port)

通过express命令创建目录结构时,您可能已经看到了这一点(下一行)

alfred@alfred-laptop:~/node$ express test4
   create : test4
   create : test4/app.js
   create : test4/public/images
   create : test4/public/javascripts
   create : test4/logs
   create : test4/pids
   create : test4/public/stylesheets
   create : test4/public/stylesheets/style.less
   create : test4/views/partials
   create : test4/views/layout.jade
   create : test4/views/index.jade
   create : test4/test
   create : test4/test/app.test.js
alfred@alfred-laptop:~/node$ cat test4/app.js 

/**
 * Module dependencies.
 */

var express = require('express');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.use(express.bodyDecoder());
  app.use(express.methodOverride());
  app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] }));
  app.use(app.router);
  app.use(express.staticProvider(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

// Routes

app.get('/', function(req, res){
  res.render('index.jade', {
    locals: {
        title: 'Express'
    }
  });
});

// Only listen on $ node app.js

if (!module.parent) {
  app.listen(3000);
  console.log("Express server listening on port %d", app.address().port)
}

在Express v3.0中,

/* No longer valid */
var app = express.createServer();
app.listen();
console.log('Server running on %s', app.address().port);

不再有效!对于Express v3.0,您应该通过以下方式创建应用和服务器:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000);
console.log('Express server started on port %s', server.address().port);

我自己遇到了这个问题,想记录新的语法。Express v3.0中的此更改和其他更改在https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x上可见

在当前版本(v0.5.0-pre)中,该端口似乎可以作为服务器对象上的属性使用,请参见http://nodejs.org/docs/v0.4.7/api/net.html#server.address

var server = http.createServer(function(req, res) {
    ...
}

server.listen(8088);
console.log(server.address());
console.log(server.address().address);
console.log(server.address().port);

输出

{ address: '0.0.0.0', port: 8088 }
0.0.0.0
8088

如果在处理请求时需要端口而应用程序不可用,则可以使用以下命令:

request.socket.localPort

如果您使用的是Express,则可以从request对象获取它:

req.app.settings.port // => 8080 or whatever your app is listening at.

我使用Express 4的这种方式:

app.listen(1337, function(){
  console.log('Express listening on port', this.address().port);
});

通过使用此方法,我不需要为侦听器/服务器使用单独的变量。

不需要http模块。

http在Express 3或4中不需要额外导入。分配结果listen()就足够了。

var server = require('express')();

server.get('/', function(req, res) {
  res.send("Hello Foo!");
});

var listener = server.listen(3000);
console.log('Your friendly Express server, listening on port %s', listener.address().port);
// Your friendly Express server, listening on port 3000

同样,这已在Express 3.5.1&4.0.0中进行了测试。http从来没有必要导入listen方法返回一个http服务器对象。
https://github.com/visionmedia/express/blob/master/lib/application.js#L531

使用最新的node.js(v0.3.8-pre):我检查了文档,检查了http.createServer()返回的服务器实例,并阅读了server.listen()的源代码...

可悲的是,端口仅作为本地变量临时存储,并在对本机方法process.binding('net')。bind()的调用中作为参数最终结束。我没有进一步看。

似乎没有比保留对您提供给server.listen()的端口值的引用更好的方法。

从旧样式转换为新(Express 3.x)样式的最简单方法是这样的:

var server = app.listen(8080);
console.log('Listening on port: ' + server.address().port);

Pre 3.x的工作原理如下:

/* This no longer works */
app.listen(8080);
console.log('Listening on port: ' + app.address().port);
req.headers.host.split(':')[1]

我也问自己这个问题,然后我来到Express 4.x指南页面查看此示例:

var server = app.listen(3000, function() {
   console.log('Listening on port %d', server.address().port);
});

您可以使用server.address().port
以下代码中的like
来获取端口号

var http = require('http');
var serverFunction = function (req, res) {

    if (req.url == '/') {
        console.log('get method');
        res.writeHead(200, { 'content-type': 'text/plain' });
        res.end('Hello World');
    }

}
var server = http.createServer(serverFunction);
server.listen(3002, function () {
    console.log('server is listening on port:', server.address().port);
});
var express = require('express');    
var app = express();
    app.set('port', Config.port || 8881);
    var server = app.listen(app.get('port'), function() {
        console.log('Express server listening on port ' + server.address().port); 
    });

Express服务器在端口8881上侦听

If you did not define the port number and you want to know on which port it is running.

let http = require('http');
let _http = http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello..!')
}).listen();
console.log(_http.address().port);

FYI, every time it will run in a different port.

The findandbind npm addresses this for express/restify/connect: https://github.com/gyllstromk/node-find-and-bind

below a simple http server and how to get the listening port

var http = require("http");
             function onRequest(request, response) {
               console.log("Request received.");
               response.writeHead(200, {"Content-Type": "text/plain"});
               response.write("Hello World");
               response.end();
             }

             var server =http.createServer(onRequest).listen(process.env.PORT, function(){
            console.log('Listening on port '); //Listening on port 8888
        });

then get the server port by using :

console.log('Express server started on port %s', server.address().port);
const express = require('express');                                                                                                                           
const morgan = require('morgan')
const PORT = 3000;

morgan.token('port', (req) => { 
    return req.app.locals.port; 
});

const app = express();
app.locals.port = PORT;
app.use(morgan(':method :url :port'))
app.get('/app', function(req, res) {
    res.send("Hello world from server");
});

app1.listen(PORT);

The easier way is just to call app.get('url'), which gives you the protocol, sub domain, domain, and port.

本文地址:http://javascript.askforanswer.com/nodejsruhehuoqufuwuqideduankou.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!