How to listen on port 80 with Node.js ?
Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project. To create a server in our backend from Node.js, we need to import ‘http’ module and then call its createServer method to create a server. The server is set to listen on the specified port and hostname. When the server is ready, the callback function is called, in this case informing us that the server is running.
Syntax:
Importing ‘http’ module
const http = require('http');
Creating Server
const server = http.createServer((req,res)=>{
// Handle request and response
});
Specify Port Number and hostname and set the server to listen to it.
server.listen(port,hostname,callback);
What happens when we listen to port 80?
The default port for HTTP is 80 – Generally, most web browsers listen to the default port.
The syntax for a server URL is:
http://{hostname}:{port}/
So if we do not mention the port in the server URL, then by default it takes it as 80. To put it simply, http://localhost/ is exactly same as http://localhost:80/
Below is the code implementation for creating a server in node and making it listen to port 80.
Javascript
const http = require( 'http' );
const port = 80;
const hostname = 'localhost' ;
const server = http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader( 'Content-Type' , 'text/plain' )
res.end( "Welcome to Geeks For Geeks" )
});
server.listen(port,hostname,()=>{
console.log(`Server running at http:
});
|
Output:
Output In-Console:
Server running at http://localhost:80/
Console output
Now run http://localhost:80/ in the browser.
Output: In-Browser:
Welcome to Geeks For Geeks
Browser output
Last Updated :
23 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...