Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3884

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T06:50:10+00:00 2024-11-26T06:50:10+00:00

Building a Backend with Node.js and Express

  • 61k

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!

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

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   
Enter fullscreen mode Exit fullscreen mode

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

  npm start   
Enter fullscreen mode Exit fullscreen mode

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   
Enter fullscreen mode Exit fullscreen mode

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}`)   })   
Enter fullscreen mode Exit fullscreen mode

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()   
Enter fullscreen mode Exit fullscreen mode

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)   })   
Enter fullscreen mode Exit fullscreen mode

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>') })   
Enter fullscreen mode Exit fullscreen mode

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) })   
Enter fullscreen mode Exit fullscreen mode

​​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}`)   
Enter fullscreen mode Exit fullscreen mode

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…

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   
Enter fullscreen mode Exit fullscreen mode

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   
Enter fullscreen mode Exit fullscreen mode

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

nodemon image

Love you scripts

You can now start the server in developer mode with:

  npm run dev   
Enter fullscreen mode Exit fullscreen mode

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

javascriptproductivitytutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.