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)?
-
You don't need to. If you don't specify a port, or set it to 0, Node will pick one at random. – Joe Clay Mar 02 '17 at 14:57
-
And how will I know that port number? – nincs12 Mar 02 '17 at 14:58
-
http://stackoverflow.com/questions/4840879/nodejs-how-to-get-the-servers-port – Joe Clay Mar 02 '17 at 15:00
-
I added app.listen(port) in my server-side js file, started node, but when I go to my site on this specified port it time outs. What might be the reason for this? – nincs12 Mar 02 '17 at 15:17
-
There's no way I can answer that without you including the code in your question. – Joe Clay Mar 02 '17 at 15:18
-
Here it is: http://imgur.com/a/PR9Am – nincs12 Mar 02 '17 at 15:24
2 Answers
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.
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())
})

- 1
- 1

- 776
- 1
- 6
- 22