This content originally appeared on DEV Community and was authored by Rodrigo Rojas
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!
Credit to TitsayFor this (hefty) blog post, our focus shifts towards the backend. That is, towards implementing functionality on the server side of our stack.
We stan Calvin & Hobbes hereStarting 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.
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.
Before we continue, let's make one small change to our scripts
object:
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.
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 = 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…
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
That’s a mouthful, so you already know what’s coming don’t you? Yep, script that ish!
Love you scriptsYou 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
Express Send
Express Library
Node.js
Nodemon utility
This content originally appeared on DEV Community and was authored by Rodrigo Rojas
Rodrigo Rojas | Sciencx (2021-10-07T20:40:20+00:00) Building a Backend with Node.js and Express. Retrieved from https://www.scien.cx/2021/10/07/building-a-backend-with-node-js-and-express/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.