Build Simple Application
Introduction
With PnPM installed, let's take few minutes to build a simple application with a web server. A key difference between this backend class and your previous frontend class is that the previous class depended on an existing remote web server. You had very little control over it and how it worked. In this class, using Node, we build everything. While not difficult, the idea is that if you need or want it, you must add it.
Video Overview
The video provides a general overview of the activity, but does not contain the detail needed to complete each process. Watch the video to obtain a general idea, but follow the written steps to complete the activity. This is the Transcript of the video.
Build the Sample Folder
- On your desktop create a new folder. I named mine sample.
- Launch VSC and open the new folder.
- Open a VSC terminal window, (Terminal > New Terminal) or (
Control + Shift + `
). - Type
pnpm init
, press "Enter". - Pnpm will now create a package.json file.
- In the terminal you will see the code that was added to the package.json file.
- Open the package.json file, find the
"main": "index.js",
line (line 5), and change the file name to be server.js. - Save and close the file.
Add Express
As mentioned earlier, node comes bare-bones. If we want/need anything, we have to add it. These add-ons are referred to as packages. Let's add one now.
- In the VSC terminal, type the following:
pnpm add express
, press "Enter". - It should only take a moment to add the package. When done, the terminal will indicate that it finished and what version of the package was installed.
- Two additional items will appear in the folder: a node_modules folder and a pnpm-lock.yaml file. Ignore both for now.
- Open the package.json file, and you will see the package has been added to the file as a "dependency".
- Save and close the file.
Add server.js
Earlier, you told the package.json file that the application server would be a file named, server.js. This is THE server that is responsible for dealing with all incoming requests and directing the application to respond. It's time to build the file.
- Using VSC, click the "New file" button or use your typical OS command (Mac: Command + N) or (Windows: Control + N) to create the file.
- Name the file, server.js, making sure it is lowercase.
- If it is not open, open it in VSC.
- At the top of the file, let's bring the Express package into "scope" and use it to create a new "application" variable. Type the following:
/* ****************************************** * This is the application server * ******************************************/ const express = require("express") const app = express()
An Explanation
- Lines 1-3 - a comment for the file. Comment your code to help yourself and others see the organization and functionality.
- Line 4 - imports the express package.
- Lines 6 - creates the "application". Notice the parentheses? This triggers the express constructor so that app is now an object with all the functionality of Express.
- Save the file.
- Next, we'll specify a host name for the server and port for it to listen on. Then, we'll type the code to start the server and console log it, to know if it worked. Type the following, beneath what you just typed:
/* ****************************************** * Server host name and port * ***************************************** */ const HOST = 'localhost' const PORT = 3000 /* *********************** * Log statement to confirm server operation * *********************** */ app.listen(PORT, () => { console.log(`trial app listening on ${HOST}:${PORT}`) })
Time to Test
The server really doesn't do anything, but we can still test to see it run.
- Save the server.js file.
- In the terminal, type
node server.js
, press "Enter". - In the terminal, a new line should be visible, "trial app listening on localhost:3000"
- Open a new browser tab and type
localhost:3000
into the URL, press "Enter". - The browser should show an error, "Cannot GET /". This means the server is running and responding to your request. It just doesn't know how to handle the request. We'll fix that next.
Add a Route
When you entered localhost:3000
into the URL, you actually sent a "GET" request to the server. By default, it wants to respond with a resource. But, it's dumb, and we haven't told it what to do about responding. Let's do that now.
- In the server.js file, between the
const app ....
and comment for the server name and port, create 3 or 4 empty lines. - Add the following to the empty lines:
/* ****************************************** * Default GET route * ***************************************** */ app.get("/", (req, res) => {res.send("Welcome home!")})
An Explanation
- Lines 1-3 code comment.
- Line 4 does a number of things. Let's look at each:
app.get()
is an Express handler. Specifically, Express is watching for a "GET" request. We'll talk more about what GET is later."/"
indicates the "route". A route is the path indicated by the URL. In this case, it is just the base URL, with nothing added.,
the comma separates the route, from the function that is responsible for delivering a response to the request.(req, res) => { ... }
is an anonymous function that takes the request and response objects as parameters. Again, we'll go into more depth later.res.send("Welcome home!")
is a method of the response object that sends a message back to the browser. It's not a web page, just a message string.
- Save the page.
Test, Take 2
Time to see if our added code provides a response instead of our previous error.
- Click in the terminal. Stop the server with your keyboard by typing
Control + C
. - When the server stops, your normal cursor line reappears.
- Start the server again, with
node server.js
, press "Enter". - Go back the browser tab, with the error and reload the page.
- You should now see the message that we instructed the server to send, "Welcome home!".
- If it worked, then you have successfully built a web server. Congratulations!
- If it didn't work, have someone else review your code, or ask for help.
- Be sure to stop the server! Just as you did in step 1.
Conclusion
This exercise introduced you to the concept of creating an application, providing a basic configuration by altering the package.json file. Then, adding packages for additional functionality. Finally, building an application server, adding directions to it and testing it. This process is fundamental to working with the backend of web services. We'll be doing much, much more of this in the rest of the course.