Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 7, 2021 08:40 pm GMT

Building a Backend with Node.js and Express

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

Love yourself

Credit to Titsay

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

Calvin and Hobbes Smock

We stan Calvin & Hobbes here

Starting our Node.js Backend

Our goal this time is to implement a backend that will work with the phonebook application weve been working on from my previous posts.

Lets 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.

package.json image

Nice package

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

Scripts

We prefer to type less

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 were 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.

NWA Express Yourself

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:

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:

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:

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.

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):

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:

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

Look at you! You made it to the end and weve 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

Billy Mays

If you like extra credit or are an overachiever like myself, then stick around for a little tool called 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

Thats a mouthful, so you already know whats coming dont you? Yep, script that ish!

nodemon image

Love you scripts

You can now start the server in developer mode with:

npm run dev

SO much better. Ok, Ive 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
Express Send
Express Library
Node.js
Nodemon utility


Original Link: https://dev.to/crrojas88/building-a-backend-with-node-js-and-express-27b5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To