Introduction to Express
Learning Objectives
We have already learned about the Node.js runtime environment and how it allows us to run JavaScript code outside of the browser. We have also learned about the Node Package Manager (npm) and how it allows us to download and use other people’s code in our own projects.
Now we will learn about Express, a Node.js framework that helps us to build web servers and APIs.
ππΌββοΈ What is a web server?
A web server is software that accepts requests for web pages, assets, APIs, and other network resources from client programs like web browsers. When a browser requests a web page, the server finds the desired content and returns the appropriate response.
πΊοΈ Explore the web server
Let’s investigate a web server made in Node.
Explore 5m
Investigate the different parts of the Node App
require
on Line 3express()
on Line 5app.get()
on Line 12, 26 and 20app.listen()
on Line 29response.send()
on Line 13 and Line 17response.json()
on Line 22
Can you work out what each those lines are doing? Write down your predictions.
ποΈ Run the Simple Server locally
Set up your copy 5m
cd
into the cyf-simple-express
directory.npm install
to install the dependencies.npm start
π‘
Localhost
http://localhost:3000
π πΏ Modify the Server
Poke around (10m)
Now try to modify the server.js
code to do something different.
Examples:
- Say “Hello Margarita”, instead of “Hello thar!”
- Make it return an array of strings as json.
- Make it return the current time
- Advanced: make it return whatever you want!
Make a Node Project
Learning Objectives
π Create a new repo
Question | Answer |
---|---|
Repository template | No template |
Owner | YOUR_GITHUB_USERNAME |
Repository name | Express-101 |
Description | My first Express web server |
Visibility | Public |
Initialize this repository with: | :white_check_mark: Add a README file |
Add .gitignore | Node |
Choose a license | MIT License |
- Click Create repository
β Clone your repo
Clone your newly made repo to your local machine. You are going to be working in this folder for the rest of the study session.
Initialize your project
π Build your project from scratch
- Open your project in VS Code
- Open the terminal
- Run
npm init -y
to initialize your project - Run
npm install express
to install Express - Commit your changes and push them to GitHub
Start your README
π Every repo needs a readme
- Open README.md in VS Code
- Add a title and description
- Add a link to the Express documentation
- Write a sentence about what you are going to build
- Commit your changes and push them to GitHub
Building the server
Learning Objectives
The first thing we need to do is build our server. You will often need to build a server when writing back-end code. You can write a server in plain JavaScript, but Express is simpler to work with.
1. Create a server.js
file
Let’s build our server! In your project, create a new file called server.js
. This is where all our server code is going to live.
touch server.js
2. import
the express
library
We just installed Express, but we need to make sure it is included in this file specifically so we can use its methods. In Node.js, when you want to use Express in another file, you must import
it.
To require Express, write the following inside server.js
:
import express from "express";
β οΈ CommonJS legacy
Sometimes you will see require
instead of import
. This is because require
is the old (CJS) way of importing packages in Node.js and not all environments (like runkit) are updated yet. If you see require
in the curriculum, probably use import
instead.
CJS syntax: const express = require("express");
MJS syntax: import express from "express";
3. Initialise the server
To initialise our server, we need to call the express()
function. This will create an Express application for us to work with.
Add the second line of code to your server.js
file:
const express = require("express");
const app = express();
4. Start ’listening’ for potential requests
One more step left, we need to set a port for our server to listen to. Think of a port as a door number: any requests that come to the server will come via that door. Setting a port will allow us to find where our server is running.
We use the app.listen
method to do this. This method takes two arguments: a port and a callback function telling it what to do once the server is running.
Need clarification? Read more about the
app.listen
method in the Express documentation.
We’re going to run our server on port 3000
, and add a console.log
in the callback function. Update your server.js
file, calling the app.listen
method:
5. Switch the server on!
You’ve built your server, but it isn’t running yet. We need to run a command in
the terminal to do this. We are going to use the node
keyword to run the
server file.
Type the following command in your terminal:
node server.js
If you see this, congratulations! You have built yourself a server!
6. npm script
To exit the running the server, type ctrl + c
. Instead of running the server with node server.js
everytime, we can create an alias for it in package.json
.
Under the scripts
property, add start: node server.js
. We can now run our server using npm start
which will be an alias (a shortcut) to node server.js
.
Go to the terminal and type npm start
and make sure that the server still runs.
Youtube: Server code-along with Mitch π
Communicating with the server
Learning Objectives
Now that we’ve built the server, we need to communicate with it. We are going to control the server with handler functions.
What is a handler function?
When a request reaches the server, we need a way of responding to it. In comes the handler function. The handler function receives requests and handles them, hence the name.
The handler function is always called with a request
and response
object. The response object is what gets sent back to the client. It contains the information that gets displayed in the web page. You can decide what to send back in your response.
What does a handler function look like in Express?
The get()
method is one of the methods used to define a handler function in Express. It takes two parameters: the endpoint at which to trigger an action, and the handler function that tells it exactly what to do.
Here’s an example:
// req is the Request object, res is the Response object
// (these are variable names, they can be anything but it's a convention to call them req and res)
app.get("/", (req, res) => {
res.send("Hello World!");
});
Here, we are telling our server to respond with “Hello World!” when someone tries to access the webpage.
1. Create your own handler function
Add a handler handler function to send back a message to the client. To do that, use the Express send()
method. This will update the response object with the message.
Update your handler function:
console.log
the request
object inside the handler function.
- Restart your server
- Send the request again with Postman
- Go to your terminal to see what it looks like.
You should see a lot of data come through!
2. Check it out in Postman
Quit your server in the terminal with ctrl + c
. Then restart it to run your new changes.
node server.js
- Open Postman
- Send a
GET
request tohttp://localhost:3000
.
If you see your message in Postman, congratulations! You just sent your first response from the server.
Checkpoint
Do you understand all these terms? You should be able to see examples of them in Postman
Routing
Learning Objectives
At the moment our server only does one thing. When it receives a request from the /
endpoint, it sends back the same response: “Yay Node!”.
π‘ tip
However by making use of endpoints, we can make the server send different responses for different requests. This concept is called routing.
What is an endpoint?
An endpoint is the part of the URL which comes after /
. For example: /chocolate
is the “chocolate” endpoint. It’s the URL to which you send a request. It’s the end point of the resource path.
What is a URL?
Create your own endpoints and send different responses
We’re going to try sending different responses at different endpoints. Remember the app.get()
method? To set up routing in your server, we need to repeat this method with different endpoints.
For example:
app.get("/", function (req, res) {
res.send("Hello World!");
});
app.get("/chocolate", function (req, res) {
res.send("Mm chocolate :O");
});
Explore 5m
/node
and another one when it’s /codeyourfuture
.Youtube: Routing Code-along with Mitch π
Query Parameters
Learning Objectives
So, what is a query parameter?
A query string is the part of a URL (Uniform Resource Locater) after the question mark (?). It is meant to send small amounts of information to the server via the url. This information is usually used as parameters to query a database, or maybe to filter results.
Here is an example of a URL with query strings attached: https://stackabuse.com/?page=2&limit=3
β Detect Query Parameters
Try sending different responses at different endpoints. Remember the app.get()
method? To set up routing in your server, we need to repeat this method with different endpoints.
app.get("/", (req, res) => {
let searchQuery = req.query.search;
res.send("Hello World! You searched for " + searchQuery);
});
Test this endpoint with query parameters: http://localhost:3000?search=hello
Now your turn!
Respond 10m
Add some code so that your server returns the amount of chocolate that you want from your /chocolate
endpoint.
π§ͺ Acceptance Criteria
Given a chocolate endpoint
When I load http://localhost:3000/chocolate?amount=3
Then I see the message “Gimme 3 chocolates!”
ββ Multiple Query Parameters
What if we want to detect and read multiple parameters? If we use a URL from earlier as an example, here is how we would send multiple query parameters:
Here we have one parameter called “lat” and another “lng”. The first parameter starts with ? All subsequent parameters start with &.
Here is how we would do that in Node:
app.get("/json", (req, res) => {
let lat = req.query.lat;
let lng = req.query.lng;
res.send(`You searched for Lat: ${lat} and Lng: ${lng}`);
});
Compute 10m
Add some code so that your server takes 2 values that we will multiply together and return the value.
π§ͺ Acceptance Criteria
Given a multiply endpoint
When I call http://localhost:3000/multiply?value1=2&value2=10
Then it returns a value of 20
Prep Non-verbal Communication
π€π½ FeedbackLearning Objectives
Introduction
Non-verbal communication is just as important as verbal communication. If we match non-verbal with verbal we can reinforce our words or vice versa. Non-verbal communication helps us spot if someone is being untruthful with us.
It is good to be aware of how non-verbal communication differs from culture to culture. Certain gestures can have different meanings depending on who you are talking to. For example a βthumbs upβ means βgood job or well doneβ in Europe or America but in the Middle East it can mean βup yoursβ. In Western cultures, eye contact is a sign of interest and confidence, and doing otherwise gives the impression of disinterest. Whereas in many Middle Eastern countries eye contact between sexes is inappropriate and in many Asian areas it can be a sign of confrontation and aggression. These are just two differences among many, so keep those in mind when communicating with people from different backgrounds to yours.
10 Types of Non-Verbal Communication
π― Goal: To get familiar with what non-verbal communication is. (45 minutes)
Read the article about 10 Types of Non-Verbal CommunicationCultural Differences
π― Goal: To reflect on your own cultural differences. (20 minutes)
After reading both of the articles:
- come up with 5 cultural differences in body language/non-verbal communication that are specific to your culture.Β
- write down how other people perceived this difference.Β
Bring them with you to the class so you can share them with other trainees.
STAR Method
π― Goal: To learn about the STAR Method. (15 minutes)
Using the STAR Method helps structure the answers and examples we give, especially in job interviews. Instead of getting caught up in details, we provide concise answers.
Read this article about the STAR Method