HTTP server in node

HTTP server in node

Hi, this is going to be a short one.

I am currently diving deep into Node.js and learning how to create a simple web server. I thought it would be nice to share my knowledge with all of you.

If you've used Express or Nest, you're probably familiar with the concept of a web server. However, I never really understood how it worked until now.

The most basic unit in creating a web server is the HTTP package. You can import it using the following line of code:

const http = require("http");

Next, we use createServer function from this package. it takes two arguments, request and response. The request object is used to handle incoming requests, while the response object is used to send a reply to those requests. Here's an example code block:

const server = http.createServer((req, res) => {
    // Add request and response code here
});

Now, in order for the server to start listening for requests, we use another method called listen. It also takes two arguments: the first is the port number, and the second is a callback function.

const PORT = 8000;

server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});

Right now we won't get anything in response when we hit the localhost:8000 as the server is not returning any response. let's add a simple hello world to createServer function.

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader("Content-Type", "text/json");
    res.end(JSON.stringify({ message: "Hello World" }));
});

Now when you start the node server using node fileName.js and hit localhost:8000 in the browser or Postman, you'll receive the following response.

{
  "message": "Hello World"
}

Here's the complete code for the experiment:

const http = require("http");

const PORT = 8000;

const server = http.createServer(async (req, res) => {
    res.statusCode = 200;
    res.setHeader("Content-Type", "text/json");
    res.end(JSON.stringify({ message: "Hello World" }));
});

server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});

Thanks and happy coding! Follow me on Twitter for more updates.