DEV Community

Ayako yk
Ayako yk

Posted on

A Beginner's Guide to HTTP Servers in Node.js

Setting up an HTTP server in Node.js is essential. There are multiple ways to do so. Axios is a great library, but today I'll focus on Node.js's built-in modules to understand the fundamentals.

HTTP
Hypertext Transfer Protocol (HTTP) is used for communication between a client and a server. HTTP servers handle requests and responses. The methods, or verbs, are GET, POST, PUT, and DELETE. They work with request and response headers and also handle streaming data.

Handling GET Requests
The example code is from the Node.js repository on GitHub.

I'll break down what each part of the code does to understand the fundamentals.

This is the overall code:

const https = require('https');

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/todos',
  method: 'GET',
};

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', error => {
  console.error(error);
});

req.end();
Enter fullscreen mode Exit fullscreen mode
const https = require('https');
Enter fullscreen mode Exit fullscreen mode

require('node:https') is a newer version (Node.js 16+). By explicitly mentioning node, it can avoid any conflicts.

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/todos',
  method: 'GET',
};
Enter fullscreen mode Exit fullscreen mode

The options object specifies the data for the request. Port 443 is the default for HTTPS; for HTTP, it is 80.

const req = https.request(options, res => {
Enter fullscreen mode Exit fullscreen mode

The res parameter is a response object that includes the status code, headers, and the actual response body.

res.on('data', d => {
Enter fullscreen mode Exit fullscreen mode

The on method is an event listener that listens for the data event emitted when a chunk of the response is received.

process.stdout.write(d);
Enter fullscreen mode Exit fullscreen mode

The process.stdout.write(d); writes the chunk of data (d) to the standard output, usually your terminal.

req.on('error', error => {
Enter fullscreen mode Exit fullscreen mode

When an error occurs, the on method is fired. Without handling an error, Node.js will crash.

req.end();
Enter fullscreen mode Exit fullscreen mode

req.end(); signals that all request data has been sent, completing the request lifecycle. This step is important to ensure the request is processed by the server.

Handling POST Requests
This is the overall code:

const https = require('https');

const data = JSON.stringify({
  todo: 'Buy the milk',
});

const options = {
  hostname: 'whatever.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length,
  },
};

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', error => {
  console.error(error);
});

req.write(data);
req.end();
Enter fullscreen mode Exit fullscreen mode
const data = JSON.stringify({
  todo: 'Buy the milk',
});
Enter fullscreen mode Exit fullscreen mode

We stringify the data to JSON to prepare it for sending.

headers: {
  'Content-Type': 'application/json',
  'Content-Length': data.length,
},
Enter fullscreen mode Exit fullscreen mode

We specify the header's format as JSON and set the length of the data.

req.write(data);
Enter fullscreen mode Exit fullscreen mode

This code writes the data to the body of the request, ensuring Buy the milk is included in the POST request.

GET Request Using createServer
The Node.js documentation shares a simple code snippet using createServer.

const { createServer } = require('node:http');

const hostname = '127.0.0.1';
const port = 3000;

const server = createServer((req, res) => { 
  res.statusCode = 200; 
  res.setHeader('Content-Type', 'text/plain'); 
  res.end('Hello World');});

server.listen(port, hostname, () => { 
  console.log(`Server running at http://${hostname}:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode
const { createServer } = require('node:http');
Enter fullscreen mode Exit fullscreen mode

The createServer method is imported and destructured from the http module, which is designed to set up an HTTP server.

const server = createServer((req, res) => { 
Enter fullscreen mode Exit fullscreen mode

For every incoming HTTP request, the callback function is executed.
req - The incoming request (e.g., URL, headers, method)
res - The outgoing response to the client

res.statusCode = 200; 
Enter fullscreen mode Exit fullscreen mode

We set the status code to ensure the client receives clear information about the request status.

res.setHeader('Content-Type', 'text/plain');
Enter fullscreen mode Exit fullscreen mode

The setHeader method is used to define headers for the response.

res.end('Hello World');});
Enter fullscreen mode Exit fullscreen mode

This line sends the body Hello World and completes the response.

server.listen(port, hostname, () => { 
Enter fullscreen mode Exit fullscreen mode

The server starts and listens for incoming connections on the specified port and hostname.

By breaking down the built-in modules, I now have a clear understanding and a solid foundation for handling HTTP requests in Node.js. This knowledge will be helpful even when using advanced third-party libraries.

Top comments (0)