-2

Was it always the case that once you generated an express application you have to set manually what port you'd like to listen to? I am just curious. It would make sense that right after I install the app I could just go ahead, start the app and it would automatically "be working" (as in I need to just navigate to my site)?

nincs12
  • 15
  • 3

2 Answers2

1

You can set which port to listen on in you app.js file, it's gonna run unless that port is busy, which can be handled by, setting which ports not to use in usual case, or configure your webserver to auto=start your app on server boot, which will reduces the possibility of the port being busy. or just edit your code to try random combinations until it finds a port.

1

Chosing Random Post For Your Server And Logging The Output In Console

As Joe Clay told you to use 0 instead of a port number it shall solve your problem, However if you wish to know details call function on server startup,

app.listen(0,'your_device_local_network_IP', () => {
    console.log(app.address())
}

It will log out the details about your server, this should be the result if you use local network IP (I personally use it to check my site across multiple device in my network)

{ address: '192.168.10.5', family: 'IPv4', port: 34488 }

You do not enter your Local network IP, emit the 'your_device_local_network_IP' which is optional, the output should be like

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

Here is my simple working Server:

let http = require('http');
let path = require('path');
let serveStatic = require('serve-static');

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


app.set('views', './views');
app.set('view engine', 'pug');

app.use('/', serveStatic('./public'));
app.get('/', (req, res) => {res.render('index')});
let server = http.createServer(app);
server.listen(0, () => {
    console.log(server.address())
})

How to set port for express server dynamically?

Community
  • 1
  • 1
Syed Huzaifa Hassan
  • 776
  • 1
  • 6
  • 22