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

发布于 2024-10-15 05:39:11 字数 414 浏览 6 评论 0原文

您经常会看到 Node 的示例 hello world 代码创建一个 Http Server,开始侦听端口,然后跟随以下内容:

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

但理想情况下您会想要这样:

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

How do Iretrieve the port the server is current Listening在调用 server.listen() 之前不将数字存储在变量中?

我以前见过这样做,但我在 Node 文档中找不到它。也许是想表达一些具体的东西?

You often see example hello world code for Node that creates an Http Server, starts listening on a port, then followed by something along the lines of:

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

But ideally you'd want this instead:

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

How do I retrieve the port the server is currently listening on without storing the number in a variable prior to calling server.listen()?

I've seen this done before but I can't find it in the Node documentation. Maybe it's something specific to express?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

巴黎夜雨 2024-10-22 05:39:11

Express 4.x 答案:

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

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

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

Express 3 答案:

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

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

当您从 表达命令:

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 4.x answer:

Express 4.x (per Tien Do's answer below), now treats app.listen() as an asynchronous operation, so listener.address() will only return data inside of app.listen()'s callback:

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

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

Express 3 answer:

I think you are looking for this(express specific?):

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

You might have seen this(bottom line), when you create directory structure from express command:

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)
}
没企图 2024-10-22 05:39:11

在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/Migration-from-2.x-to-3.x

In express v3.0,

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

no longer works! For Express v3.0, you should create an app and a server this way:

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

I ran in to this issue myself and wanted to document the new syntax. This and other changes in Express v3.0 are visible at https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x

花心好男孩 2024-10-22 05:39:11

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

request.socket.localPort

In case when you need a port at the time of request handling and app is not available, you can use this:

request.socket.localPort
残月升风 2024-10-22 05:39:11

在当前版本(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

In the current version (v0.5.0-pre) the port seems to be available as a property on the server object, see 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);

outputs

{ address: '0.0.0.0', port: 8088 }
0.0.0.0
8088
↘紸啶 2024-10-22 05:39:11

我使用这种方式 Express 4:

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

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

I use this way Express 4:

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

By using this I don't need to use a separate variable for the listener/server.

蒲公英的约定 2024-10-22 05:39:11

如果您使用的是express,您可以从请求对象中获取它:

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

If you're using express, you can get it from the request object:

req.app.settings.port // => 8080 or whatever your app is listening at.
多像笑话 2024-10-22 05:39:11

从来不需要 http 模块。

在 Express 3 或 4 中不需要额外导入 http。分配 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 和 Express 3.5.1 中进行测试的。 4.0.0。从来没有必要导入 http。 Listen 方法返回一个 http 服务器对象。
https://github.com/visionmedia/express/blob/master /lib/application.js#L531

Requiring the http module was never necessary.

An additional import of http is not necessary in Express 3 or 4. Assigning the result of listen() is enough.

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

Again, this is tested in Express 3.5.1 & 4.0.0. Importing http was never necessary. The listen method returns an http server object.
https://github.com/visionmedia/express/blob/master/lib/application.js#L531

无声情话 2024-10-22 05:39:11

如果您没有定义端口号并且您想知道它在哪个端口上运行。

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

仅供参考,每次它都会在不同的端口运行。

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.

黑凤梨 2024-10-22 05:39:11
req.headers.host.split(':')[1]
req.headers.host.split(':')[1]
权谋诡计 2024-10-22 05:39:11
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

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 server listening on port 8881

野稚 2024-10-22 05:39:11

您可以使用server.address().port获取端口号
就像下面的代码一样:

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

You can get the port number by using server.address().port
like in below code:

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);
});
烟若柳尘 2024-10-22 05:39:11

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

遗憾的是,该端口仅临时存储为局部变量,并最终作为调用 process.binding('net').bind() 的参数,这是一个本机方法。我没有再看下去。

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

With latest node.js (v0.3.8-pre): I checked the documentation, inspected the server instance returned by http.createServer(), and read the source code of server.listen()...

Sadly, the port is only stored temporarily as a local variable and ends up as an argument in a call to process.binding('net').bind() which is a native method. I did not look further.

It seems that there is no better way than keeping a reference to the port value that you provided to server.listen().

陪你搞怪i 2024-10-22 05:39:11

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

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

在 3.x 之前,它的工作方式如下:

/* This no longer works */
app.listen(8080);
console.log('Listening on port: ' + app.address().port);

The simplest way to convert from the old style to the new (Express 3.x) style is like this:

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

Pre 3.x it works like this:

/* This no longer works */
app.listen(8080);
console.log('Listening on port: ' + app.address().port);
俏︾媚 2024-10-22 05:39:11

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

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

I was asking myself this question too, then I came Express 4.x guide page to see this sample:

var server = app.listen(3000, function() {
   console.log('Listening on port %d', server.address().port);
});
标点 2024-10-22 05:39:11

findandbind npm 为express/restify/connect 解决了这个问题:https: //github.com/gyllstromk/node-find-and-bind

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

稚然 2024-10-22 05:39:11
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);
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);
半城柳色半声笛 2024-10-22 05:39:11

您可能正在寻找process.env.PORT。这允许您使用所谓的“环境变量”动态设置侦听端口。 Node.js 代码如下所示:

const port = process.env.PORT || 3000; 
app.listen(port, () => {console.log(`Listening on port ${port}...`)}); 

您甚至可以使用 export PORT=5000 或任何您想要的端口在终端中手动设置动态变量。

You might be looking for process.env.PORT. This allows you to dynamically set the listening port using what are called "environment variables". The Node.js code would look like this:

const port = process.env.PORT || 3000; 
app.listen(port, () => {console.log(`Listening on port ${port}...`)}); 

You can even manually set the dynamic variable in the terminal using export PORT=5000, or whatever port you want.

我早已燃尽 2024-10-22 05:39:11

快递 v4+

const app = require("express")();
app.listen( 5555, function() {
  console.log( this.address().port )
})

express v4+

const app = require("express")();
app.listen( 5555, function() {
  console.log( this.address().port )
})
她说她爱他 2024-10-22 05:39:11
Using express

const express = require("express")
const app=express();
app.listen(3000, ()=>{
console.log("Listening to post 3000");
}
using HTTP
const http=require('http');

const server = http.createServer((req, res), ()=>{
res.end("am server")
})
server.listen(3000, ()=>{
console.log("Listening to post 3000");
})
Using express

const express = require("express")
const app=express();
app.listen(3000, ()=>{
console.log("Listening to post 3000");
}
using HTTP
const http=require('http');

const server = http.createServer((req, res), ()=>{
res.end("am server")
})
server.listen(3000, ()=>{
console.log("Listening to post 3000");
})
心意如水 2024-10-22 05:39:11

更简单的方法是调用 app.get('url'),它会为您提供协议、子域、域和端口。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文