Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express: How do you get the hostname and port that an express server is listening on, WITHOUT waiting for a request

It's fairly straight forward to get the hostname and URL from a request that has been made to an express server. But there seems to be no obvious way to determine which URL an express server is listening on (after it has been started up, but before any requests have been sent).

How do you find out which host and port an express server is listening on? Does express even know which host and port it is listening on?

like image 904
Fergie Avatar asked Dec 09 '16 08:12

Fergie


People also ask

How do I find my hostname in Express?

We can use the req. hostname property to get the hostname from a current incoming request in express. Example: const express = require("express"); const app = express(); app.

How do I listen to a port in Express?

listen() function is used to bind and listen the connections on the specified host and port. This method is identical to Node's http. Server. listen() method.

What port should I use for Express server?

I know that Express apps default to port 3000.

What is the default port for Express?

A small disadvantage is that, when generating the code, we do not know how to change some very basic things, for example, the port on which the app listens (the default port is 3000). In this post I will show you how to change the port in some app generated by express-generator.


1 Answers

If you create an server like this:

  var server = http.createServer(app);

The server instance actually contains the port and address it's listening. So you could just export it, and call server.address() to get the address and port.

  { address: '::', family: 'IPv6', port: 3200 }

If you want further info about what urls are your routes are routing, try

  console.log(router.stack)

then the magic happens. :)

like image 56
YLS Avatar answered Oct 12 '22 23:10

YLS