Home > Back-end >  Node.js Automatically set current port
Node.js Automatically set current port

Time:02-26

require('http').createServer((req,res)=>{res.end();}).listen(80);

listen Is it possible to automatically set this to the current port?

listen(address().port)

do not enter port or wildcard Automatically obtain listen(auto) current port.

CodePudding user response:

The correct way to start a server with http is like this.

const http = require('http');

const server = http.createServer((req, res) => {
    res.end();
})

server.listen(port, hostname, () => {
    console.log(`Server is listening... https://${hostname}:${port}/`)
})

You can take a look at the doc

CodePudding user response:

There is no such thing as "the current port" for a server. A server IP address can be used on a wide range of ports, there is no "current port" for an IP address.

You must specify the port you want your server to run on. That's up to you as a developer to determine. The most common port for an http server is port 80 and for an https server 443, but you can pick other port numbers if you have a particular reason to.

CodePudding user response:

In NodeJS the .listen(<port>, <address>, <callback>) can accept a port number, IP address and a callback function. However, it is possible to call the method with no arguments at all. In this option NodeJS will use a random, unused port number on localhost address.

For example, the following block of code is valid:

const http = require("http");

const server = http.createServer((req, res) => {
  console.log(req);
});

server.listen();

you can inspect the port and IP address of your server by writing:

console.log(server.address());
  • Related