Express
Today we will learn how to build web applications with Express.
Contents
- Section 1: HTTP, Express, and Postman
- Section 2. Queries, Parameters, and Status codes
- Section 3. Templating and Handlebars
- Section 4. HTML Forms
Section 1: HTTP, Express, and Postman
Watch me: Express Introduction
Watch me: HTTP Introduction + Postman
Section 1a. Postman
Install Postman and make a
GETrequest tohttps://horizons-postman.herokuapp.com/When you are successful you will see a message in the output panel:
Great, you're starting the Postman warmup exercise!Make a
GETrequest tohttps://horizons-postman.herokuapp.com/1(note the/1at the end) with the request parameterpostmanset toexcellent.You can do this by either editing the URL directly or clicking on
Paramsand adding a key and value.You should see:
ScreenshotSuccess. Part 1 complete
Now we can make a
PUTrequest with some JSON contents. We put the contents of the request in the Body section and change theContent-Typeheader so the server knows how to interpret the data.- Make a request to
https://horizons-postman.herokuapp.com/2 - Set method to
PUT Set the body to be
Screenshotrawadd the content{ "foods": ["bacon", "lettuce", "tomato"] }
Set header
ScreenshotContent-Typetoapplication/json
You should see
Success. Part 2 complete- Make a request to
Section 1b. Express GET routes
- Open your terminal and navigate to the
/5_express/1_express_intro/folder - Run
npm install - Open
/5_express/1_express_intro/server.jsin your favourite text editor. - Require the
expresslibrary (var express = require('expres')) - Initialize your express app instance (
var app = express()) - Create the following routes:
GET /: Send the string"The Horizons Poet API v1.0".GET /api/*: Send the string"We couldn’t find any routes matching this endpoint".*denotes any string (i.e./api/anything,/api/unicorn,/api/p/r/a/t/h, etc.)- you will need to use
app.use()for this
GET /api/poem: Send the text from the file/5_express/1_express_intro/poem.txt- use the following code to read
poem.txtjs var fs = require('fs'); var poem = fs.readFileSync('./poem.txt', 'utf8');
- use the following code to read
POST /api/success: Send the json{success: true}usingres.json()
- Listen on port 3000
- Use Postman to verify all the routes you have created. You can
connect to your local server at http://localhost:3000
Section 2. Queries, Parameters, and Status codes
Watch me: HTTP Queries and Parameters
Watch me: Status Codes
- Open this folder (
/5_express/1_express_intro/express_echo) in your Terminal on Mac or Git Bash on Windows. - Install dependencies with NPM:
bash npm install - Open
app.jsin your editor of choice and add an express http endpoint so that it prints correctly on step 5 (follow the directions in theapp.jsfile). - Start your server. Note: When you change
app.jsyou have to restart it to see your changes!bash npm start Verify that your code is working correctly by opening http://localhost:3000/hello?name=Simba in Chrome. It should print:
Hello there Simba!Stop your server with Control+C in your Terminal/PowerShell.
Section 3. Templating and Handlebars
Section 3a. Setting up Handlebars
Watch me: Express Templating
The following set of tasks will require setting up your own express app with handlebars templating. You should refer back to the video if you get stuck on a task.
- Navigate to
/5_express/1_express_intro/handlebars_examples/hello_world/: This is the folder you will be working in - Start your Node App (you can use
npm init) - Install the required packages
expressexpress-handlebars
- Create an
app.jsfile: This is where you will set up express to use handlebars - Create the following routes:
/: Displays the text"Hello World"from a.hbsfile/:error: Displays the text"<error> page not found, did you enter the correct url?"where<error>is the text entered as a param.- Example:
/aboutwill render a handlebars page with the textabout page not found, did you enter the corrent url?.
- Example:
- Run your node app and make sure the above routes work!
Section 3b. If-Else in Handlebars
Watch me: If-Else Handlebars
Open
/5_express/1_express_intro/handlebars_examples/conditional/app.jsand note how the/:wordendpoint is implemented.This endpoint renders
condition.hbswith the following data:{ isEven: Boolean, // true if word has even number of letters word: String // the word entered at :word }Edit
Odd letter screenshot/5_express/1_express_intro/handlebars_examples/conditional/views/condition.hbsand display<h1>The word <entered-word-here> has an even number of letters!</h1>ifisEvenis true, otherwise display<h1>The word <entered-word-here> has an odd number of letters!</h1>![odd]
Even letter screenshot![even]
Watch me: Looping in Handlebars
- Open
/5_express/1_express_intro/handlesbars_examples/profiles/in your Terminal - Run
npm install - Take a look at
data.json; this is a list of student info that contiansfirst_name,last_name,email, andgender. - Create a Handlebars template under
viewsthat, given an array of students, displays their first name, last name, and email in a list. - Create the following routes that render the template you created in the
previous step:
/: A directory of ALL students/male: A directory of ALL MALE students/female: A directory of ALL FEMALE students
- Run
node app.jsto serve your handlebars files onlocalhost:3000 - Make sure your above routes work as intended!
Section 4. HTML Forms
Section 4a. Input Fields & Names
Watch Me: Input Fields & Names
- Open
/5_express/1_express_intro/forms_examples/: For this example you will write code in the following filesexample1.jsviews/example1.hbs
- Create a
GET /route that renders a page with a header and a form.h1: A heading tag that's text is based on the input box (in the form).form: A form with aninputbox and a submit button
Test your route by running
npm installthennode example1.jsin the terminal. Th e following steps should work:- Open your favourite web browser and navigate to
localhost:3000 You should see a heading titled Default Header and a input box with a submit button (like below)
Screenshot![form_1_1]
Type Change The Header into the input box and press submit
The heading should change to Change The Header like below
Screenshot![form_1_2]
- Open your favourite web browser and navigate to
Section 4b. Form Action Attribute
Watch Me: Form Action Attribute
In this example you are to make a register form. Make sure that when you press submit, the form data does not change (use the value attribute).
- Open
/5_express/1_express_intro/forms_examples/: For this example you will write code in the following files -example2.js-views/example2.hbs - Create a register form (in
views/example2.hbs) with the following inputs:- username (text input box)
- password (password input box)
- name (text input box)
- gender: male/female/other (radio buttons)
- BONUS state (dropdown)
- BONUS Add logic in
example2.jsto make sure the data in your form will NOT be cleared when you press Register. npm install && node example2.jsto test your app.Fill in the form (it should look something like the one below once filled) and click register. Make sure the form stays filled.
Screenshot![form_2_1]
Section 4c. Form Method Attribute
Watch Me: Form Method Attribute
Now for this example we're going to implement login functionality for our users. You are to create a Login Form which contains an email and password field. The list of accounts (along with their passwords) are stored as JSON in accounts.js.
- Open
/5_express/1_express_intro/forms_examples/: For this example you will write code in the following filesexample3.jsviews/example3.hbs
- Create a login form (in
views/example3.hbs) with the following inputs:- email (text input field)
- password (password input field)
- Add functionality for your form to
POSTto/loginon submit In
example3.jscreate aPOSTroute at/loginwhich usesreq.bodyto check if the entered email/password fields are inaccounts.json- Given correct credentials render a
h1tag that says"Hi [insert-first-name-here]!"(example below). NOTE that first name can be found inaccounts.json - Given incorrect credentials render a RED error message on your page.
![form_3_1]
- Given correct credentials render a
Fill in the form with random credentials and make sure the error message pops up
Fill in the form with someone's credentials from
accounts.jsand press Login. You should see the correct heading for that person pop up!
Woohoo! You've completed the individual exercises for the day!
Log in or sign up for Devpost to join the conversation.