What does http and https module do in Node?

Viewed 645

Can someone help me in understanding what does http and https module do in Express?

I was going through the following docs on w3schools

From definition it says

Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).

With following example

var 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

This is the example to live demo

First, I am unable to comprehend their example like Where are they making (route) request so that they are receiving response?

Second by the definition, to make a request, using libraries like axios can be alternative?

third, when we make an api request, isn't the data transferred over http/https?

app.post("/", (req, res) =>  {

In short, Can someone please explain me in more human words the use of http package in express?

Update: I might be confusing this with express, I am used to using express and here we aren't using express

1 Answers

1- They aren't defining any route. That piece of code only creates a server running on port 8080 that when it's created or accessed on the home route (/) returns "Hello World". If you want to define routes you should take a closer look to a module called express that it's used by most of node users due to its simplicity and documentation (https://expressjs.com/en/starter/hello-world.html) In that link you have an example for creating the server and a basic route

2- Yes it can and should be because they are way better than the default from nodeJs. Take a look at axios or superagent, superagent it's better if you want to use formdata to send images or attachments.

3- By default, all servers created using http or express are http servers (don't have a certificate to encrypt the data so they aren't secure). If you want a https server, you can buy certificates or use https://letsencrypt.org/ this module that generates free SSL certificates with 1 month validation.

http module has multiple functions, it can be used to create a server, to make http requests and so on. It's up to you to decide which submodule from the package you want to use. Express is built over the http module making everything easier.

If you need more explanation, tell me and I will try to explain a little better.

Related