SWE 432 -Web
Application Week 4:
Development Backend
Development
Fall 2022
George Mason
University
Dr. Kevin Moran
Administrivia
•HW Assignment 1 - Grades Available on
Blackboard - Detailed Comments in Replit
•HW Assignment 2 - Due October 4th
Before Class - will discuss next week
2
Class Overview
•(Today) Backend Programming: A Brief
History and Intro to Express with [Link].
•(Next Week) Part 2 -Handling HTTP
Requests: Exploring HTTP and REST
3
Review
4
Review: Async Programming Example
1 second each
Go get a candy Go get a candy Go get a candy Go get a candy Go get a candy
bar bar bar bar bar
Go get a candy Go get a candy Go get a candy Go get a candy Go get a candy
bar bar bar bar bar
thenCombine
2 seconds each
Group all 3 Group all Group all Group all
Group all Twix
Musketeers MilkyWay MilkyWay Dark Snickers
when done
Eat all the Twix
5
Async/Await
• Rules of the road:
• You can only call await from a function that is async
• You can only await on functions that return a Promise
• Beware: await makes your code synchronous!
async function getAndGroupStuff() {
...
ts = await [Link](stuff,"t");
...
}
6
In-Class Example
Rewrite this code so that all of the things are fetched (in parallel) and then all of the groups are collected using async/await
7
In-Class Example
8
Backend Web Development
9
A Brief Intro and History of Backend
Programming
10
Why We Need Backends
• Security: SOME part of our code needs to be “trusted”
• Validation, security, etc. that we don’t want to allow users to bypass
• Performance:
• Avoid duplicating computation (do it once and cache)
• Do heavy computation on more powerful machines
• Do data-intensive computation “nearer” to the data
• Compatibility:
• Can bring some dynamic behavior without requiring much JS support
11
Dynamic Web Apps
i th
w
c ts
t e ra
ri n Web “Front End”
e u se Presentation
th
t Frontend programming
ha
W Web “Front
next weekEnd” Some logic
i th
w
c ts
t e ra
i n
n d
n te
f ro
the “Back End”
W h a t
Data storage
Persistent Some other
Storage APIs Some other logic
12
Where Do We Put the Logic?
with
ra cts
te
e r in Web “Front End” Presentation
us
the
at
Wh Some logic
th
wi
cts
ntera
ndi “Back End” Data storage
e
nt
fro
he
a tt Persistent Some Some other logic
Wh Storage other APIs
Backend Pros
Frontend Pros Easy to refactor between multiple
Very responsive (low latency) clients
Logic is hidden from users (good for
Frontend Cons security, compatibility, etc.)
Security
Performance Backend Cons
Unable to share between front-ends Interactions require a round-trip to
server
13
Why Trust Matters
• Example: Banking app
• Imagine a banking app where the following code runs in the browser:
function updateBalance(user, amountToAdd)
{
[Link] = [Link] + amountToAdd;
}
• What’s wrong?
• How do you x that?
14
fi
What Does our Backend Look Like?
Our own backend
AJAX
Connection to
Web “Front End”
Frontend
Logic
Persistent Data
15
The “Good” Old Days of Backends
HTTP Request
GET /myApplicationEndpoint HTTP/1.1
Host: [Link]
Accept: text/html
web server
Runs a program
Give me /myApplicationEndpoint
Does whatever it wants My
Web Server
Application
Application
Here’s some text to send back Backend
HTTP Response
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
<html><head>...
16
What’s wrong with this picture?
17
History of Backend Development
• In the beginning, you wrote whatever you wanted using whatever
language you wanted and whatever framework you wanted
• Then… PHP and ASP
• Languages “designed” for writing backends
• Encouraged spaghetti code
• A lot of the web was built on this
• A whole lot of other languages were also springing up in the 90’s…
• Ruby, Python, JSP
18
Microservices vs. Monoliths
• Advantages of microservices over monoliths include
• Support for scaling
• Scale vertically rather than horizontally
• Support for change
• Support hot deployment of updates
• Support for reuse
• Use same web service in multiple apps
• Swap out internally developed web service for externally developed web service
• Support for separate team development
• Pick boundaries that match team responsibilities
• Support for failure
19
Support for Scaling
Frontend
Backend Server
Mod 1 Mod 2
Our Cool App
Mod 3 Mod 4
Mod 5 Mod 6
Database
20
Now How Do We Scale It?
Frontend
Backend Server Backend Server Backend Server
Mod 1 Mod 2 Mod 1 Mod 2 Mod 1 Mod 2
Our Cool App
Mod 3 Mod 4 Mod 3 Mod 4 Mod 3 Mod 4
Mod 5 Mod 6 Mod 5 Mod 6 Mod 5 Mod 6
Database
We run multiple copies of the backend, each with each of the modules
21
What's wrong with this picture?
• This is called the
“monolithic” app
Frontend
• If we need 100 servers… Backend Server Backend Server Backend Server
Mod 1 Mod 2 Mod 1 Mod 2 Mod 1 Mod 2
• Each server will have to run Mod 3 Mod 4
Our Cool App
Mod 3 Mod 4 Mod 3 Mod 4
EACH module Mod 5 Mod 6 Mod 5 Mod 6 Mod 5 Mod 6
• What if we need more of
Database
some modules than others?
22
Microservices
NodeJS, Firebase Google Service Java, MySQL
Todos Accounts Mailer
REST REST REST
service service service
Our Cool App Mod 1 Mod 2 Mod 3
Frontend
Database Database Database
“Dumb” AJAX
Backend
Search Engine Analytics Facebook Crawler
REST REST REST
service service service
Mod 4 Mod 5 Mod 6
Database Database Database
23 Java, Neo4J C#, SQLServer Python, Firebase
Goals of Microservices
• Add them independently
• Upgrade the independently
• Reuse them independently
• Develop them independently
• ==> Have ZERO coupling between microservices, aside from their
shared interface
24
[Link]
• We’re going to write backends with [Link]
• Why use Node?
• Event based: really ef cient for sending lots of quick updates to lots of
clients
• Very large ecosystem of packages, as we've seen
• Why not use Node?
• Bad for CPU heavy stuff
25
fi
Express
• Basic setup:
• For get:
[Link]("/somePath", function(req, res){
//Read stuff from req, then call [Link](myResponse)
});
• For post:
[Link]("/somePath", function(req, res){
//Read stuff from req, then call [Link](myResponse)
});
• Serving static les:
[Link]([Link]('myFileWithStaticFiles'));
• Make sure to declare this *last*
• Additional helpful module - bodyParser (for reading POST data)
[Link]
26
fi
Demo: Hello World Server
1: Make a directory, myapp Creates a con guration le
for your project
2: Enter that directory, type npm init (accept all defaults)
3: Type npm install express --save Tells NPM that you want to use
4: Create text le [Link]: express, and to save that in your
project con g
var express = require('express');
var app = express();
var port = [Link] || 3000;
[Link]('/', function (req, res) {
[Link]('Hello World!');
});
[Link](port, function () {
[Link]('Example app listening on port' + port);
});
5: Type node [Link]
6: Point your browser to [Link] Runs your app
27
fi
fi
fi
fi
Demo: Hello World Server
var express = require(‘express'); // Import the module express
var app = express(); // Create a new instance of express
var port = [Link] || 3000; // Decide what port we want express to listen on
[Link]('/', function (req, res) { // Create a callback for express to call
[Link]('Hello World!'); when we have a “get” request to “/“.
}); That callback has access to the request
(req) and response (res).
[Link](port, function () {
[Link]('Example app listening on port' + port); // Tell our new instance of
express to listen on port, and
});
print to the console once it
starts successfully
28
Demo: Hello World Server
29
Demo: Hello World Server
30
Core Concept: Routing
• The de nition of end points (URIs) and how they respond to client
requests.
• [Link](PATH, HANDLER)
• METHOD: all, get, post, put, delete, [and others]
• PATH: string (e.g., the url)
• HANDLER: call back
[Link]('/', function (req, res) {
[Link]('Got a POST request');
});
31
fi
Route Paths
• Can specify strings, string patterns, and regular expressions
• Can use ?, +, *, and ()
• Matches request to root route
[Link]('/', function (req, res) {
[Link]('root');
});
• Matches request to /about
[Link]('/about', function (req, res) {
[Link]('about');
});
• Matches request to /abe and /abcde
[Link]('/ab(cd)?e', function(req, res) {
[Link]('ab(cd)?e');
});
32
Route Parameters
• Named URL segments that capture values at speci ed location in URL
• Stored into [Link] object by name
• Example
• Route path /users/:userId/books/:bookId
• Request URL [Link]
• Resulting [Link]: { "userId": "34", "bookId": "8989" }
[Link]('/users/:userId/books/:bookId', function(req, res)
{
[Link]([Link]);
});
33
fi
Route Handlers
• You can provide multiple callback functions that behave like
middleware to handle a request
• The only exception is that these callbacks might invoke next('route') to
bypass the remaining route callbacks.
• You can use this mechanism to impose pre-conditions on a route,
then pass control to subsequent routes if there’s no reason to proceed
with the current route.
[Link]('/example/b', function (req, res, next) {
[Link]('the response will be sent by the next function ...')
next()
}, function (req, res) {
[Link]('Hello from B!')
})
34
Request Object
• Enables reading properties of HTTP request
• [Link]: JSON submitted in request body (must de ne body-
parser to use)
• [Link]: IP of the address
• [Link]: URL query parameters
35
fi
HTTP Responses
• Larger number of response codes (200 OK, 404 NOT FOUND)
• Message body only allowed with certain response status codes
“OK response”
Response status codes:
1xx Informational
2xx Success
3xx Redirection
4xx Client error
5xx Server error
“HTML returned
content”
Common MIME types:
application/json
application/pdf
image/png
36 [HTML data]
Response Object
• Enables a response to client to be generated
• [Link]() - send string content
• [Link]() - prompts for a le download
• [Link]() - sends a response w/ application/json Content-Type header
• [Link]() - sends a redirect response
• [Link]() - sends only a status message
• [Link]() - sends the le at the speci ed path
[Link]('/users/:userId/books/:bookId', function(req, res) {
[Link]({ “id”: [Link] });
});
37
fi
fi
fi
Describing Responses
• What happens if something goes wrong while handling HTTP request?
• How does client know what happened and what to try next?
• HTTP offers response status codes describing the nature of the response
• 1xx Informational: Request received, continuing
• 2xx Success: Request received, understood, accepted, processed
• 200: OK
• 3xx Redirection: Client must take additional action to complete request
• 301: Moved Permanently
• 307: Temporary Redirect
[Link]
38
Describing Errors
• 4xx Client Error: client did not make a valid request to server. Examples:
• 400 Bad request (e.g., malformed syntax)
• 403 Forbidden: client lacks necessary permissions
• 404 Not found
• 405 Method Not Allowed: speci ed HTTP action not allowed for resource
• 408 Request Timeout: server timed out waiting for a request
• 410 Gone: Resource has been intentionally removed and will not return
• 429 Too Many Requests
39
fi
Describing Errors
• 5xx Server Error: The server failed to ful ll an apparently valid
request.
• 500 Internal Server Error: generic error message
• 501 Not Implemented
• 503 Service Unavailable: server is currently unavailable
40
fi
Error Handling in Express
• Express offers a default error handler
• Can speci c error explicitly with status
• [Link](500);
41
fi
Persisting Data in Memory
• Can declare a global variable in node
• i.e., a variable that is not declared inside a class or function
• Global variables persist between requests
• Can use them to store state in memory
• Unfortunately, if server crashes or restarts, state will be lost
• Will look later at other options for persistence
42
Making HTTP Requests
• May want to request data from other servers from backend
• Fetch
• Makes an HTTP request, returns a Promise for a response
• Part of standard library in browser, but need to install library to use in backend
• Installing:
npm install node-fetch --save
• Use:
const fetch = require('node-fetch');
fetch('[Link]
.then(res => [Link]())
.then(body => [Link](body));
var res = await fetch('[Link]
[Link]
43
Responding Later
• What happens if you'd like to send data back to client in response,
but not until something else happens (e.g., your request to a
different server nishes)?
• Solution: wait for event, then send the response!
fetch('[Link]
.then(res => [Link]())
.then(body => [Link](body));
44
fi
Acknowledgements
Slides adapted from Dr. Thomas LaToza’s
SWE 632 course
45