My Development Notes


How to create and run your very first simple HTTP server in NodeJS?

NodeJS

The first thing to do is to create a JS file inside your code editor. Next we write the following codes :

const http = require('http');

In the above code we’ve imported the HTTP Module which is required for creating the server.

In the following steps, let’s write some more codes :

const server = http.createServer((req, res) => {
  res.end('Replying from the server!');
});

server.listen(7500, '127.0.0.1', () => {
  console.log('This server is live!');
});

In the above code block we’ve used the http.createServer() method to create a server on your computer which displays a message when we run the server.listen() method. Again, inside the server.listen() method the first parameter is the PORT (which is 7500 in this case), the second parameter is hostname (127.0.0.1) and the third parameter is of course a callback function.

Note: req and res means request and response.

Now, in order to run the server you’ll need to run the following code inside the terminal:

node index.js

Next, open a web browser and type http://127.0.0.1:7500 for the server to start running, displaying the message ‘Replying from the server!’ in our case.

There are many other ways to create a simple server using HTTP module. Here’s another way to do it :

// Import the http module
const http = require('http');

// Define the port number
const PORT = 7500;

// Create a server instance
const server = http.createServer((req, res) => {
  // Set the response header
  res.writeHead(200, {'Content-Type': 'text/plain'});

  // Send the response body
  res.end('Replying from the server!');
});

// Start the server and listen on the defined port
server.listen(PORT, () => {
  console.log('This server is live!');
});


// the server will still run on the same port and hostname

This is the barebone structure to create a very basic HTTP Server inside your local computer using NodeJS.


Leave a Reply

Your email address will not be published. Required fields are marked *