Getting to Know Node.js (Part IV)
Tags: node
Published: 2020-11-25 06:04:49

---
title: 'Getting to Know Node.js (Part IV)'
published: true
description: 'Part IV - The HTTP Server'
tags: nodejs
series: 'Getting to Know Node.js'
cover_image: https://images.pexels.com/photos/169647/pexels-photo-169647.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940
---

Hello! I hope you've managed to chill out a bit after all the excitement of [last time](https://dev.to/oaluna/getting-to-know-node-js-part-iii-4hac) where I covered the npm CLI and the Node Package Manager registry. This week I will move on to cover how to make requests to the HTTP server.

##HTTP##

HTTP, or HyperText Transfer Protocol, is the standard architecture for how we send and receive hypermedia documents to the server from the client (the browser).  Through Node's `http` interface we can easily handle several types of features, such as data caching, building pipelines, or providing authorization upon a successful login. 

##But what the heck is a server?##

A web server is defined as a process running on hardware that listens for requests and sends back responses. In short, the browser makes HTTP requests to a server, and the server response with the resources needed to render HTML on the client. Say you are navigating to a website. The browser makes a request to the site's web server, using the HTTP protocol, requesting for site resources. Multiple resources are provided as new content is requested. 
 Node.js lets us build both the backend server along with the request methods and response data to communicate with it. 

```
const http = require(‘http’);

const port = process.env.PORT || 3000;

const server = http.createServer((req, res) => {
  res.end();
});
server.on('error', (err) => {
res.json(400);
console.error(err)
};
});

server.listen(port, () => {
  console.log(`Server running at port ${port}`);
});

```
In the example above we start with requiring `http`, one of Node's core modules containing functions which simplify interacting with the server. After importing the module we declared a `port` variable to equate to `process.env.PORT`, or 3000. The `createServer` function creates our server object. This function receives `request` and `response` events as arguments. In our callback we can set our response headers with `res.writeHead()`. Here we can set properties like a response status code, response content-type, and response headers. Since our server above requires none of that, our server object jumps right to the response body, which returns a callback when our request is completed.

It's a good practice to have an error handler listening in the event of an error in the request (ie. A bad request, an unauthorized one, the requested resources couldn't be found, etc.). In our example we have our server listen for an error, using `http.listen`, upon which it will return an error 400 (unauthorized) message to the console. However, upon a successful request, the server returns a message indicating that it is listening at our port (3000).

I'll be honest; there's no clear-cut way to define a server, let alone make requests to it. You have options. But one of the more popular ways of creating web servers is the Express.js framework. It comes with built-in HTTP methods and middleware for creating APIs, as well as starting a server. 

```
//call the top-level express application exported by Express
const express = require('express');
const app = express();

const port = process.env.PORT || 4000;

//route a GET request to '/' with a series of middleware functions
app.get('/', (req, res) => res.send('Hello World'));

//Listen for connections on our defined path
app.listen(port, () => console.log(`Server is listening on port ${port}`));

``` 
Here we use the function `express()`, which is passed to the server to handle requests. We can also route different methods of HTTP requests (GET, PUT, POST, etc.) this way. Then, we mount our middleware function, containing the `req` and `res` parameters, to the `/` path. These are comparable to the request and response events, in that they are used to handle our requests and responses, ie. performing application logic. 

Well, readers, I will leave this here for now, and next time we'll dive deeper into Express.js routing. I'm still getting the hang of this blogging business -- so excuse the delay between now and the last. Until next time! 

---

**Works Cited**

> 1. Haverbeke, Martin "Node.js", *Eloquent JavaScript - A Modern Introduction to Programming*, 3rd Edition, 2019, Chapter 20, No Starch Press, Inc.
> 2. https://docs.npmjs.com

---