Building a Backend with Node.js and Express
Tags: javascript, tutorial, productivity, webdev
Published: 2021-10-07 20:40:20

Hey there. I know I’ve been MIA for a couple of months and I promised I’d be more active with posting. The truth is, sometimes life just catches up with you and you gotta take care of yourself first. But I’m here now, so let’s get started!

<figure>
![Love yourself](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oabr3e7wdddkyqzgx7je.jpeg)
<figcaption>Credit to <a href="https://www.inprnt.com/gallery/titsay/what-do-i-do-with-all-this-love/">Titsay</a></figcaption>
</figure>

For this (hefty) blog post, our focus shifts towards the backend. That is, towards implementing functionality on the server side of our stack. 

<figure>
![Calvin and Hobbes Smock](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6kgkqr3asddlftgbjwuy.jpg)
<figcaption>We stan Calvin & Hobbes here</figcaption>
</figure>

## Starting our Node.js Backend

Our goal this time is to implement a backend that will work with the phonebook application we’ve been working on from my [previous posts](https://dev.to/crrojas88/make-http-get-requests-with-axios-23id).

Let’s create a new template for our application with the `npm init` command. We will answer the questions presented and the result will be a generated `package.json` file that contains information about the project.

<figure>
![package.json image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojxwowda1as57vju7f6q.png)
<figcaption>Nice package</figcaption>
</figure>

Before we continue, let's make one small change to our `scripts` object:

<figure>
![Scripts](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gpaone97krmpa975kk2n.png)
<figcaption>We prefer to type less</figcaption>
</figure>

We _could_ run the application directly with `node` from the command line like so:

```
node index.js
```

**OR** we can run it as an npm script because we’re fancy/lazy like that:

```
npm start
```

The `npm start` script works because we defined it in the package.json file!

## Using the Express Framework

In order to ease server-side development with node and offer an easier interface to work with the built-in http module, we can use a backend framework called [Express](http://expressjs.com/).

![NWA Express Yourself](https://thumbs.gfycat.com/ImmaterialAggressiveAmericanmarten-size_restricted.gif)

Let's install express as a project dependency with the following command which in turn will be added to our `package.json` file:

```
npm install express
```

The primary purpose of our backend server will be to offer raw data in the `JSON` format to the frontend. For this reason, we can now change our `index.js` file to return a hardcoded list of people in the `JSON` format along with some express functionality:

```javascript
const express = require('express')
const app = express()

let people = [
    {
      name: "Hannah Rickard",
      number: "06-51-99-56-83",
      id: 1
    },
    {
      name: "Hyun Namkoong",
      number: "10987654",
      id: 2
    },
    {
      name: "Courtney Martinez",
      number: "3691215",
      id: 3
    }
  ]

  app.get('/', (request, response) => {
      response.send('<h1>Phonebook</h1>')
  })

  app.get('/api/people', (request, response) => {
      response.json(people)
  })

  const PORT = 3001
  app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`)
  })
```

Right off the bat, at the beginning of our `index.js` we import express, which is a function that is used to create an express application stored in the `app` variable:

```JavaScript
const express = require('express')
const app = express()
```

Now, we define two `routes` to the application. The first one defines an event handler that is used to handle HTTP `GET` requests made to the application's `/` route:

```javascript
app.get('/', (request, response) => {
      response.send('<h1>Phonebook</h1>')
  })

  app.get('/api/people', (request, response) => {
      response.json(persons)
  })
```

The event handler function accepts two parameters.

* The first request parameter contains all of the information of the `HTTP` request.
* The second response parameter is used to define how the request is responded to.

For our first instance, the request is answered by using the `send` method of the response object. Calling the method makes the server respond to the `HTTP` request by sending a response containing the string `<h1>Phonebook</h1>`, that was passed to the `send` method.

```javascript
app.get('/', (request, response) => {
  response.send('<h1>Phonebook</h1>')
})
```
Now for the second instance, our route defines an event handler that handles HTTP `GET` requests made to the `/people` path of our app (this should look familiar to you if not, refresh your memory [here](https://dev.to/crrojas88/make-http-get-requests-with-axios-23id)):

```javascript
app.get('/api/people', (request, response) => {
  response.json(people)
})
```

​​The `GET` request is responded to with the `json` method of the response object. Calling this method will send the people array that was passed to it as a JSON formatted string. How neat is that?

Finally, the last rows bind the `HTTP` server assigned to the app variable, to listen to HTTP requests sent to the `PORT 3001`:

```javascript
const PORT = 3001
app.listen(PORT)
console.log(`Server running on port ${PORT}`)
```
Look at you! You made it to the end and we’ve now managed to make two `GET` requests using express. One to our `/` route, and another to our `people` route. In our following posts we will expand the app to uphold RESTful conventions.

## Before You Go…

<figure>
![Billy Mays](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1mu97yxl18xg7bk41klv.jpeg)
</figure>

If you like extra credit or are an overachiever like myself, then stick around for a little tool called [Nodemon](https://github.com/remy/nodemon). What is Nodemon you ask? Well, according to the documentation:

_nodemon will watch the files in the directory in which nodemon was started, and if any files change, nodemon will automatically restart your node application._

Usually when we make changes to our backend code we have to painstakingly restart the application in order to see the changes with `Ctrl+C` and then relaunching with `npm start`.

Compared to the convenient workflow in React where the browser automatically reloads after changes are made, this feels slightly **annoying**. But have no fear, nodemon will take care of us. 

Changes to the backend code now cause the server to restart automatically (You'll still have to refresh the browser though).

To start, install nodemon and define it as a development dependency:

```
npm install --save-dev nodemon
```

A dev what now? When we say development dependencies, we mean tools that are needed only during the development of the application. In our case, for automatically restarting the backend.

To summon nodemon we simply:

```
node_modules/.bin/nodemon index.js
```

That’s a mouthful, so you already know what’s coming don’t you? Yep, script that ish!

<figure>
![nodemon image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rbjwxps88vb5r2yut9xf.png)
<figcaption>Love you scripts</figcaption>
</figure> 

You can now start the server in developer mode with:

```
npm run dev
```

**SO** much better. Ok, I’ve rambled long enough. Check back for when we start to build our backend so it can fetch a single resource, delete, and even receive new data! Remember to take breaks and hydrate. Rod out.

### Resources:
[Express & JSON](http://expressjs.com/en/4x/api.html#res.json)
[Express Send](http://expressjs.com/en/4x/api.html#res.send)
[Express Library](http://expressjs.com/)
[Node.js](https://nodejs.org/en/)
[Nodemon utility](https://github.com/remy/nodemon)