Open In App

How to listen on port 80 with Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Importing 'http' module 
const http = require('http');
  
// Setting Port Number as 80 
const port = 80;
  
// Setting hostname as the localhost
// NOTE: You can set hostname to something 
// else as well, for example, say 127.0.0.1
const hostname = 'localhost';
  
// Creating Server 
const server = http.createServer((req,res)=>{
  
    // Handling Request and Response 
    res.statusCode=200;
    res.setHeader('Content-Type', 'text/plain')
    res.end("Welcome to Geeks For Geeks")
});
  
// Making the server to listen to required
// hostname and port number
server.listen(port,hostname,()=>{
  
    // Callback 
    console.log(`Server running at http://${hostname}:${port}/`);
});


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
Previous
Next
Share your thoughts in the comments
Similar Reads