HTTP – Node.js

Introduction

Do you ever think how can we create a bridge between what we build in the front-end and our back-end code?! How the magic happens!!! If you are still wondering, let’s introduce you to the HTTP protocol.

What is HTTP? Why do we need to use it and when ?

HTTP || Hypertext Transfer Protocol is a protocol for fetching resources such as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser. A complete document is reconstructed from the different sub-documents fetched, for instance, text, layout description, images, videos, scripts, and more.

It was designed for communication between web browsers and web servers, but it can also be used for other purposes.

Learning objectives

  • What is HTTP protocol.
  • What is a web server?
  • HTTP Node module.
  • How to a basic web-server with Node.js using the HTTP module.
  • Identify common HTTP Methods.
  • Describe the Request – Response cycle.
  • How to make an API request in Node.js?
  • HTTP Status Code.

Study

What is a Web Server?

Basically, a web server is a computer that runs websites. A web server is used to store, process, and deliver the web pages to users. Communication with a web server is done by using HTTP requests. When a user makes a request for a website through an URL to the internet, a DNS converts the URL to an IP address that points to the targeted server.

Different Types of Web Server

There are mainly 4 types of web servers:

  • Apache HTTP Web Server.
  • Internet Information Services ( IIS) Web Server.
  • Nginx Web Server.
  • LightSpeed Web Server.

The Node.js HTTP Module

The Built-in HTTP Module

  • Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).
  • The HTTP core module is a key module to Node.js networking.
  • To include the HTTP module, use the require() method:
let http = require('http');

The module provides some properties and methods, and some classes.

How to build HTTP server

Node.js as a Web Server

The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.

Use the createServer() method to create an HTTP server:

let http = require('http');
//create a server object:
http.createServer(function (req, res) {
  res.write('Hello World!'); //write a response to the client
  res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

The function passed into the http.createServer() method, will be executed when someone tries to access the computer on port 8080.

HTTP Request Methods:

HTTP requests are messages sent by the client to initiate an action on the server. And these requests are sent by some HTTP methods. The most commonly used HTTP Request Methods are GET, POST, PUT, PATCH, DELETE.

GET

GET is used to request data from a specified resource.

  • It is only used to request data.
  • It can’t modify or post data to the web server.
  • GET requests should not be used when dealing with sensitive data.
  • GET requests have length restrictions on data.
  • GET requests are cached, it remains in the browser history.
POST

POST requests are used when data is sent to a server to create/update a resource. The data sent to the server with POST is stored in the request body of the HTTP request. POST requests are never cached. POST requests don’t have any length restrictions.

PUT

PUT requests are also used to send data to a server to update a resource. The difference between POST and PUT is that PUT requests are idempotent. That is, calling the same PUT request multiple times will always produce the same result. In contrast, calling a POST request repeatedly have side effects of creating the same resource multiple times.

PATCH

PATCH request is used to update or modify data. It is used to apply partial modification to the target resource. On the other hand, PUT requests replace the full target resource with the data that is sent via that request.

DELETE

DELETE request is used to delete a specified resource from a database.

Node.js Network Requests

3 ways to make HTTP requests in Node.js

In the modern technological world, it is very rare to find stand-alone applications. Most applications depend on resources from other applications. These resources are made available through the use of APIs. Servers are no exception. Though servers store their own relevant data, they sometimes need data from other servers. To access the data, servers need a way to communicate with the API(s) of the depended servers.

  • Let’s take a look at three options on how to make an HTTP request, there are many more available.:

    • HTTP — the default

    • Fetch (node-fetch)

    • Axios

Example on how to use Axios

  • first you need to install Axios in your project npm install axios
// import node-fetch
const axios = require('axios');
// set url as constant
const URL = 'https://jsonplaceholder.typicode.com/todos';
axios
  .get(URL)
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });

Read This article and implement the three examples:Important

HTTP status code

When client’s request to the server, server provide a HTTP (Hypertext Transfer Protocol) response status code, Which allows us to understand what is happening on the back-end of a website, determine what errors need to be fixed.

All HTTP response status codes are parted into five categories. The first digit of the status code defines the categories of response. There are five values for the first digit:

  • 1xx (Informational):Request initiated by the browser is continuing.
  • 2xx (Successful): The request was successfully received, understood, and processed by the server.
  • 3xx (Redirection):Requested information that is no longer at the provided address, further action needs to be taken in order to complete the request.
  • 4xx (Client Error):When there was a problem with the request of client.
  • 5xx (Server Error): When client made a valid request, but the server is unable to complete the transfer.

Resources

Additional resources

In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.

Videos