Video 4.1 Intro to Node.js Environment Setup Chris Murphy · 2019. 6. 19. · • Node.js and...

Post on 01-Sep-2020

6 views 0 download

Transcript of Video 4.1 Intro to Node.js Environment Setup Chris Murphy · 2019. 6. 19. · • Node.js and...

Video 4.1

Intro to Node.js Environment Setup

Chris Murphy

SD4x-4.1 1

Property of Penn Engineering, Chris Murphy

Review: How does a Web Browser Work?

• The World Wide Web utilizes Hypertext Transfer Protocol (HTTP) to transfer documents

Client Server

Client sends request

Server sends response

1

2

2SD4x-4.1

Property of Penn Engineering, Chris Murphy

Review: How does a Web Browser Work?

• The World Wide Web utilizes Hypertext Transfer Protocol (HTTP) to transfer documents

Client Server

Client sends request

Server sends response

1

2

3SD4x-4.1

Property of Penn Engineering, Chris Murphy

Review: How does a Web Browser Work?

• The World Wide Web utilizes Hypertext Transfer Protocol (HTTP) to transfer documents

Client Server

Client sends request

Server sends response

1

2

4SD4x-4.1

Property of Penn Engineering, Chris Murphy

What does the Web Server do?

• Listen for and accept incoming HTTP requests

• Parse the HTTP request to determine what is being requested

• Locate (and/or create) the resource being requested

• Construct and send back the HTTP response

SD4x-4.1 5

Property of Penn Engineering, Chris Murphy

Node.js

• Asynchronous, event-driven JavaScript runtime environment for building web applications

• Treats HTTP requests as events that invoke callback functions/handlers that construct the HTTP response

• Also includes a package manager to simplify the deployment of JavaScript apps

SD4x-4.1 6

Property of Penn Engineering, Chris Murphy

Installing Node.js

• You can install Node.js by downloading, running, and finishing the package installer available here:

• https://nodejs.org/en/download/

• Check that installation is correct using: node –v

• Update modules using: npm install npm –g

SD4x-4.1 7

Property of Penn Engineering, Chris Murphy

Setting up a new project

• Create a new folder for your project

• Use Terminal, Command Prompt, etc. to navigate to that folder

• Set up a new project by running: npm init

• You will be prompted to enter some information about your project

• Specify “index.js” as your entry point

SD4x-4.1 8

Property of Penn Engineering, Chris Murphy

Setting up a new project

• Your project folder should now have a package.json configuration file

{

"name": "helloworld",

"version": "1.0.0",

"description": "A basic hello world app",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "edX Learner",

"license": "ISC"

}

SD4x-4.1 9

Property of Penn Engineering, Chris Murphy

Express

• Express is a web application framework that sits on top of a Node.js server

• Express helps you modularize and streamline your web application

• Within Express, you can organize your app in many ways:

• Define separate modules that have different responsibilities

• Handle requests via different routes and routers

• Split each step in the processing of a request into Middlewares

SD4x-4.1 10

Property of Penn Engineering, Chris Murphy

Adding Express

• To use Express, run the following from the folder where you created your Node.js app: npm install express --save

• The Express package will be downloaded to the project and added to your package.json file as a dependency

• Package: a package is a module of JavaScript code, usually with a specific purpose, that can be re-used and assembled with other modules

• Dependency: A dependency is a piece of code that your program relies on to work correctly

SD4x-4.1 11

Property of Penn Engineering, Chris Murphy

Express Configuration

• Your package.json file will now have a new section called dependencies

• npm can refer to this in the future and re-download or update your packages as needed

SD4x-4.1 12

{

"name": "helloworld",

"version": "1.0.0",

"description": "A basic hello world app",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "edX Learner",

"license": "ISC",

"dependencies": {

"express": "^4.15.3"

}

}

Property of Penn Engineering, Chris Murphy

Express Configuration

• Your package.json file will now have a new section called dependencies

• npm can refer to this in the future and re-download or update your packages as needed

SD4x-4.1 13

{

"name": "helloworld",

"version": "1.0.0",

"description": "A basic hello world app",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "edX Learner",

"license": "ISC",

"dependencies": {

"express": "^4.15.3"

}

}

Property of Penn Engineering, Chris Murphy

Express Configuration

• Your package.json file will now have a new section called dependencies

• npm can refer to this in the future and re-download or update your packages as needed

SD4x-4.1 14

{

"name": "helloworld",

"version": "1.0.0",

"description": "A basic hello world app",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "edX Learner",

"license": "ISC",

"dependencies": {

"express": "^4.15.3"

}

}

Property of Penn Engineering, Chris Murphy

Express Configuration

• Your package.json file will now have a new section called dependencies

• npm can refer to this in the future and re-download or update your packages as needed

SD4x-4.1 15

{

"name": "helloworld",

"version": "1.0.0",

"description": "A basic hello world app",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "edX Learner",

"license": "ISC",

"dependencies": {

"express": "^4.15.3"

}

}

Property of Penn Engineering, Chris Murphy

Express Configuration

• Your package.json file will now have a new section called dependencies

• npm can refer to this in the future and re-download or update your packages as needed

SD4x-4.1 16

{

"name": "helloworld",

"version": "1.0.0",

"description": "A basic hello world app",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "edX Learner",

"license": "ISC",

"dependencies": {

"express": "^4.15.3"

}

}

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 17

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 18

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 19

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 20

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 21

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 22

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 23

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 24

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 25

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 26

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 27

Property of Penn Engineering, Chris Murphy

Hello World

• Create an file named index.js in your Node.jsproject root directory with the following contents:

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.1 28

Property of Penn Engineering, Chris Murphy

Running Express

• In the project folder, run: node index.js

• When the server starts, you should see “Listening on port 3000” written to the console/screen

• Open a browser on the same computer and go to http://localhost:3000/

SD4x-4.1 29

Property of Penn Engineering, Chris Murphy SD4x-4.1 30

Property of Penn Engineering, Chris Murphy

Looking Ahead

• How can the server send different responses for different requests?

• How can the server dynamically generate responses?

• How does the server interact with external data sources?

SD4x-4.1 31

Video 4.2

Node.js Request and Response Objects

Chris Murphy

SD4x-4.2 32

Property of Penn Engineering, Chris Murphy

Review

• Web browsers communicate with Web servers via HTTP requests and responses

• Node.js and Express simplify the development of Web servers to handle HTTP requests and create and return HTTP responses

SD4x-4.2 33

Property of Penn Engineering, Chris Murphy

Anatomy of an HTTP Request

GET /examples/index.html HTTP/1.1

Host: www.edx.org

User-Agent: Mozilla/4.0

Accept-Language: en-us

Content-Length: 9

a=12&b=34

Request Verb URI HTTP Version

Request Line

Request Headers

Blank Line Separator

Request Message Body

34SD4x-4.2

Property of Penn Engineering, Chris Murphy

Node.js/Express Request Objects

• An HTTP Request is represented as an object in the Express app

• The object is passed as a parameter to the callback function/event handler

SD4x-4.2 35

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy

Node.js/Express Request Objects

• An HTTP Request is represented as an object in the Express app

• The object is passed as a parameter to the callback function/event handler

SD4x-4.2 36

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy

Node.js/Express Request Objects

• An HTTP Request is represented as an object in the Express app

• The object is passed as a parameter to the callback function/event handler

SD4x-4.2 37

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy

Node.js/Express Request Objects

• An HTTP Request is represented as an object in the Express app

• The object is passed as a parameter to the callback function/event handler

SD4x-4.2 38

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy

Request Object Properties/Functions

SD4x-4.2 39

app.use('/', (req, res) => {

var method = req.method;

var url = req.url;

var agent = req.headers['user-agent'];

agent = req.get('User-Agent');

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Properties/Functions

SD4x-4.2 40

app.use('/', (req, res) => {

var method = req.method;

var url = req.url;

var agent = req.headers['user-agent'];

agent = req.get('User-Agent');

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Properties/Functions

• method: the HTTP Request verb/action

SD4x-4.2 41

app.use('/', (req, res) => {

var method = req.method;

var url = req.url;

var agent = req.headers['user-agent'];

agent = req.get('User-Agent');

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Properties/Functions

• method: the HTTP Request verb/action

• url: the resource that was requested

SD4x-4.2 42

app.use('/', (req, res) => {

var method = req.method;

var url = req.url;

var agent = req.headers['user-agent'];

agent = req.get('User-Agent');

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Properties/Functions

• method: the HTTP Request verb/action

• url: the resource that was requested

• headers: object containing all headers

SD4x-4.2 43

app.use('/', (req, res) => {

var method = req.method;

var url = req.url;

var agent = req.headers['user-agent'];

agent = req.get('User-Agent');

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Properties/Functions

• method: the HTTP Request verb/action

• url: the resource that was requested

• headers: object containing all headers

• get(field): request header field

SD4x-4.2 44

app.use('/', (req, res) => {

var method = req.method;

var url = req.url;

var agent = req.headers['user-agent'];

agent = req.get('User-Agent');

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Anatomy of an HTTP Response

HTTP/1.1 200 OK

Date: Fri, 06 Apr xxxx 09:30:00 GMT

Server: Apache/1.4

Last-Modified: Wed, 04 Apr xxxx

Connection: close

Content-Type: text/html

Content-Length: 228

<!DOCTPYE html><html><head>….

HTTP Version Status Code

Response Line

Response Headers

Blank Line Separator

Response Body (Resource)

45

Property of Penn Engineering, Chris Murphy

Node.js/Express Response Objects

• An HTTP Response is also represented as an object in the Express app

• The object is passed as a parameter to the callback function/event handler

SD4x-4.2 46

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy

Node.js/Express Response Objects

• An HTTP Response is also represented as an object in the Express app

• The object is passed as a parameter to the callback function/event handler

SD4x-4.2 47

var express = require('express');

var app = express();

app.use('/', (req, res) => {

res.send('Hello World!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy

Response Object Functions

SD4x-4.2 48

app.use('/', (req, res) => {

res.status(200);

res.type('html');

res.write('Hello world!');

res.write('<p>');

res.write('<b>Have a nice day</b>');

res.end();

});

Property of Penn Engineering, Chris Murphy

Response Object Functions

SD4x-4.2 49

app.use('/', (req, res) => {

res.status(200);

res.type('html');

res.write('Hello world!');

res.write('<p>');

res.write('<b>Have a nice day</b>');

res.end();

});

Property of Penn Engineering, Chris Murphy

Response Object Functions

• status: set the HTTP status code

SD4x-4.2 50

app.use('/', (req, res) => {

res.status(200);

res.type('html');

res.write('Hello world!');

res.write('<p>');

res.write('<b>Have a nice day</b>');

res.end();

});

Property of Penn Engineering, Chris Murphy

Response Object Functions

• status: set the HTTP status code

• type: set the HTTP content type

SD4x-4.2 51

app.use('/', (req, res) => {

res.status(200);

res.type('html');

res.write('Hello world!');

res.write('<p>');

res.write('<b>Have a nice day</b>');

res.end();

});

Property of Penn Engineering, Chris Murphy

Response Object Functions

• status: set the HTTP status code

• type: set the HTTP content type

• write: add content to the body of the response

SD4x-4.2 52

app.use('/', (req, res) => {

res.status(200);

res.type('html');

res.write('Hello world!');

res.write('<p>');

res.write('<b>Have a nice day</b>');

res.end();

});

Property of Penn Engineering, Chris Murphy

Response Object Functions

• status: set the HTTP status code

• type: set the HTTP content type

• write: add content to the body of the response

SD4x-4.2 53

app.use('/', (req, res) => {

res.status(200);

res.type('html');

res.write('Hello world!');

res.write('<p>');

res.write('<b>Have a nice day</b>');

res.end();

});

Property of Penn Engineering, Chris Murphy

Response Object Functions

• status: set the HTTP status code

• type: set the HTTP content type

• write: add content to the body of the response

SD4x-4.2 54

app.use('/', (req, res) => {

res.status(200);

res.type('html');

res.write('Hello world!');

res.write('<p>');

res.write('<b>Have a nice day</b>');

res.end();

});

Property of Penn Engineering, Chris Murphy

Response Object Functions

• status: set the HTTP status code

• type: set the HTTP content type

• write: add content to the body of the response

• end: send the response and close the connection

SD4x-4.2 55

app.use('/', (req, res) => {

res.status(200);

res.type('html');

res.write('Hello world!');

res.write('<p>');

res.write('<b>Have a nice day</b>');

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 56

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 57

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 58

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 59

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 60

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 61

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 62

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 63

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 64

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 65

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 66

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 67

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 68

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 69

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 70

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 71

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 72

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Combining Requests and Responses

SD4x-4.2 73

app.use('/', (req, res) => {

var name = req.query.name; // e.g. /?name=devesh

res.status(200).type('html');

if (name) {

res.write('Hi, ' + name + "it's nice to see you.");

}

else {

res.write('Welcome, guest!');

}

res.end();

});

Property of Penn Engineering, Chris Murphy

Summary

• Node.js and Express represent HTTP requests and responses using JavaScript objects

• We can use these objects’ properties and functions to dynamically generate the content that is sent in response to a request

SD4x-4.2 74

Video 4.3

Express Routing

Chris Murphy

SD4x-4.3 75

Property of Penn Engineering, Chris Murphy

Review

• Node.js and Express represent HTTP requests and responses using JavaScript objects

• We can use these objects’ properties and functions to dynamically generate the content that is sent in response to a request

SD4x-4.3 76

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 77

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 78

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 79

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 80

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 81

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 82

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 83

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 84

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 85

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 86

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 87

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 88

Property of Penn Engineering, Chris Murphy

Express Routing

var express = require('express');

var app = express();

app.use('/about', (req, res) => {

res.send('This is the about page.');

});

app.use('/login', (req, res) => {

res.send('This is the login page.');

});

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 89

Property of Penn Engineering, Chris Murphy

Express Middleware

• A middleware is a function that is invoked in the handling of an HTTP request

• It is used in the “middle” between receiving a request and sending a response

• Multiple middlewares can be chained together on the same request

SD4x-4.3 90

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 91

• The simplest middleware is express.static, which serves static files that are locally stored

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 92

• The simplest middleware is express.static, which serves static files that are locally stored

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 93

• The simplest middleware is express.static, which serves static files that are locally stored

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 94

• The simplest middleware is express.static, which serves static files that are locally stored

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 95

• The simplest middleware is express.static, which serves static files that are locally stored

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 96

• The simplest middleware is express.static, which serves static files that are locally stored

Property of Penn Engineering, Chris Murphy SD4x-4.3 97

<!-- This is files/index.html -->

<html>

<body>

<h1>Hello!</h1>

<img src="images/kitty.jpg">

<!-- File is files/images/kitty.jpg -->

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.3 98

<!-- This is files/index.html -->

<html>

<body>

<h1>Hello!</h1>

<img src="images/kitty.jpg">

<!-- File is files/images/kitty.jpg -->

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.3 99

<!-- This is files/index.html -->

<html>

<body>

<h1>Hello!</h1>

<img src="images/kitty.jpg">

<!-- File is files/images/kitty.jpg -->

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.3 100

<!-- This is files/index.html -->

<html>

<body>

<h1>Hello!</h1>

<img src="images/kitty.jpg">

<!-- File is files/images/kitty.jpg -->

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.3 101

<!-- This is files/index.html -->

<html>

<body>

<h1>Hello!</h1>

<img src="images/kitty.jpg">

<!-- File is files/images/kitty.jpg -->

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.3 102

<!-- This is files/index.html -->

<html>

<body>

<h1>Hello!</h1>

<img src="images/kitty.jpg">

<!-- File is files/images/kitty.jpg -->

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.3 103

<!-- This is files/index.html -->

<html>

<body>

<h1>Hello!</h1>

<img src="images/kitty.jpg">

<!-- File is files/images/kitty.jpg -->

</body>

</html>

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 104

• We can use the response object to send back specific HTML files as needed

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 105

• We can use the response object to send back specific HTML files as needed

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).send('Not found!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 106

• We can use the response object to send back specific HTML files as needed

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 107

• We can use the response object to send back specific HTML files as needed

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 108

• We can use the response object to send back specific HTML files as needed

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 109

• We can use the response object to send back specific HTML files as needed

Property of Penn Engineering, Chris Murphy

Middleware: Serving Static Files

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.3 110

• We can use the response object to send back specific HTML files as needed

Property of Penn Engineering, Chris Murphy

Defining and Using Middleware

• Middleware functions can contain any amount of JavaScript code with any functionality

• They take three parameters: req, res, and next

• next() must be called at the end of the function to invoke the next middleware or the final response

SD4x-4.3 111

Property of Penn Engineering, Chris Murphy SD4x-4.3 112

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

app.use(logger);

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 113

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

app.use(logger);

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 114

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

app.use(logger);

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 115

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

app.use(logger);

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 116

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

app.use(logger);

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 117

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

app.use(logger);

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 118

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

app.use(logger);

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 119

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

app.use(logger);

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 120

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

app.use(logger);

app.use('/public', express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 121

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

// app.use(logger);

app.use('/public', logger, express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 122

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

// app.use(logger);

app.use('/public', logger, express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 123

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

// app.use(logger);

app.use('/public', logger, express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 124

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

// app.use(logger);

app.use('/public', logger, express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy SD4x-4.3 125

var express = require('express');

var app = express();

var logger = (req, res, next) => {

var url = req.url;

var time = new Date();

console.log('Received request for ' + url +

' at ' + time);

next();

};

// app.use(logger);

app.use('/public', logger, express.static('files'));

app.use( /*default*/ (req, res) => {

res.status(404).sendFile(__dirname + '/404.html');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

Property of Penn Engineering, Chris Murphy

Middleware Chaining

• Middleware functions are called in the order in which they are specified

• Each uses the same Request and Response objects

• A middleware function can modify the Request so that it can then be used by subsequent middleware functions “downstream” in the route

SD4x-4.3 126

Property of Penn Engineering, Chris Murphy SD4x-4.3 127

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 128

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 129

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 130

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 131

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 132

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 133

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 134

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 135

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 136

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 137

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 138

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 139

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 140

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 141

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 142

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 143

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 144

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 145

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 146

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 147

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 148

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 149

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 150

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 151

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 152

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 153

var nameFinder = (req, res, next) => {

var name = req.query.name;

if (name) req.username = name.toUpperCase();

else req.username = 'Guest';

next();

}

var greeter = (req, res, next) => {

res.status(200).type('html');

res.write('Hello, ' + req.username);

next();

}

var adminName = (req, res, next) => {

req.username = 'Admin';

next();

}

app.use('/welcome', nameFinder, greeter,

(req, res) => { res.end(); } );

app.use('/admin', adminName, greeter,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy

Middleware, Routes, and Routers

• We may find that the same combinations of middleware functions are being used in multiple routes

• We can combine middleware functions into “sub-routes” using Routers and then use those in our routes

SD4x-4.3 154

Property of Penn Engineering, Chris Murphy SD4x-4.3 155

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 156

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 157

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 158

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 159

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 160

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 161

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 162

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 163

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 164

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 165

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 166

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 167

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 168

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 169

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 170

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 171

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 172

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 173

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 174

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 175

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 176

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 177

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 178

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, header,

greeter, footer, (req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 179

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, commonRoute,

(req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 180

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, commonRoute,

(req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 181

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, commonRoute,

(req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 182

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, commonRoute,

(req, res) => { res.end(); } );

app.use('/admin', logger, adminName, header,

greeter, footer, (req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy SD4x-4.3 183

var nameFinder = (req, res, next) => { . . . }

var greeter = (req, res, next) => { . . . }

var adminName = (req, res, next) => { . . . }

var logger = (req, res, next) => { . . . }

var header = (req, res, next) => { . . . }

var footer = (req, res, next) => { . . . }

var commonRoute = express.Router();

commonRoute.use(header, greeter, footer);

app.use('/welcome', logger, nameFinder, commonRoute,

(req, res) => { res.end(); } );

app.use('/admin', logger, adminName, commonRoute,

(req, res) => { res.end(); } );

Property of Penn Engineering, Chris Murphy

Summary

• Routing allows us to specify different functionality for different HTTP requests

• Routing uses middleware functions, each of which handles a different part of the functionality

• Middleware functions can be chained together and can pass values to each other by modifying the Request object

• Routers allow us to combine middleware functions into common “sub-routes”

SD4x-4.3 184

Video 4.4

Getting User Data

Chris Murphy

SD4x-4.4 185

Property of Penn Engineering, Chris Murphy

Review

• Node.js and Express allow us to build server-side web apps in JavaScript

• HTTP Requests and Responses are represented as JavaScript objects

• We can display content based on different routes through the app

SD4x-4.4 186

Property of Penn Engineering, Chris Murphy

Getting Data from Users: HTTP Requests

• Query parameters

• Key/value pairs that are part of the URL

• Can be part of a static URL or be generated by an HTML form using the “GET” method

• POST data

• Key/value pairs that are included in the body of the HTTP request

• Result from an HTML form using the “POST” method

SD4x-4.4 187

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 188

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 189

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 190

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 191

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 192

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 193

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 194

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 195

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 196

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 197

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 198

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 199

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 200

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Query Properties

• An HTTP Request object can include queryproperties that come from the URL

http://localhost:3000/?name=Lydia&location=United+States

SD4x-4.4 201

app.use('/', (req, res) => {

var query = req.query;

console.log(query);

var name = query.name; // 'Lydia'

var location = query.location; // 'United States'

var length = Object.keys(query).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 202

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 203

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 204

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 205

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 206

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 207

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 208

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 209

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 210

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 211

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 212

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 213

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 214

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 215

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 216

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 217

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

Request Object Parameters

• An HTTP Request object can include paramproperties that come from a parameterized URL

http://localhost:3000/name/Lydia/location/United States

SD4x-4.4 218

app.use('/name/:userName/location/:userLocation',

(req, res) => {

var params = req.params;

console.log(params);

var name = params.userName; // 'Lydia'

var location = params.userLocation; // 'United States'

var length = Object.keys(params).length; // 2

res.send('Hello World!');

});

Property of Penn Engineering, Chris Murphy

HTML Forms

• Forms allow users to enter or select data, e.g. via input boxes, checkboxes, radio buttons, etc.

• The form specifies the action and method that result when the user chooses to submit the form

• Action: the URL to be requested

• Method: the HTTP Request “verb,” e.g. GET or POST

SD4x-4.4 219

Property of Penn Engineering, Chris Murphy SD4x-4.4 220

Property of Penn Engineering, Chris Murphy SD4x-4.4 221

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 222

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 223

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 224

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 225

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 226

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 227

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 228

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 229

Property of Penn Engineering, Chris Murphy

Reading POST Data in Express

• When a form’s method is “GET”, the data is sent in the URL query parameters

• When a form’s method is “POST”, the data is sent in the body of the HTTP request

• To read the body of the HTTP request in Express, use the body-parser middleware

• To install it, run: npm install body-parser

SD4x-4.4 230

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 231

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 232

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 233

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 234

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 235

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 236

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 237

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 238

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 239

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 240

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 241

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 242

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 243

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 244

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 245

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 246

Property of Penn Engineering, Chris Murphy

<html>

<body>

<form action="/handleForm" method="post">

Name: <input name="username">

<p>

I like:<br>

<input type=checkbox name="animal" value="dogs">Dogs <br>

<input type=checkbox name="animal" value="cats">Cats <br>

<input type=checkbox name="animal" value="birds">Birds <br>

<p>

<input type=submit value="Submit form!">

</form>

</body>

</html>

SD4x-4.4 247

Property of Penn Engineering, Chris Murphy

var express = require('express');

var app = express();

app.use('/public', express.static('files'));

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = req.body.animal; // this is an array

. . .

res.send('Thank you!');

});

app.listen(3000, () => {

console.log('Listening on port 3000');

});

SD4x-4.4 248

Property of Penn Engineering, Chris Murphy

Summary

• HTTP Request query properties: key/value pairs that come from URL

• HTTP Request param properties: key/value pairs that come from parameterized URL

• HTTP Request body properties: input data from form submitting using POST method

SD4x-4.4 249

Video 4.5

EJS

Chris Murphy

SD4x-4.5 250

Property of Penn Engineering, Chris Murphy

Review

• Node.js and Express allow us to build server-side web apps in JavaScript

• HTTP Requests and Responses are represented as JavaScript objects

• We can get data from user either via the URL or through form submissions

SD4x-4.5 251

Property of Penn Engineering, Chris Murphy SD4x-4.5 252

Property of Penn Engineering, Chris Murphy SD4x-4.5 253

Property of Penn Engineering, Chris Murphy SD4x-4.5 254

Property of Penn Engineering, Chris Murphy SD4x-4.5 255

Property of Penn Engineering, Chris Murphy SD4x-4.5 256

Property of Penn Engineering, Chris Murphy SD4x-4.5 257

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 258

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 259

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 260

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 261

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 262

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 263

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 264

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 265

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 266

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 267

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 268

Property of Penn Engineering, Chris Murphy SD4x-4.5 269

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 270

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 271

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 272

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 273

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 274

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 275

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 276

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 277

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 278

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 279

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy

What is EJS?

• EJS, or EmbeddedJS, is a view engine that uses data and embedded JavaScript to produce HTML

• This allows webpages to be developed statically and rendered dynamically server-side

• EmbeddedJS is a package that can be installed with the command: npm install ejs

SD4x-4.5 280

Property of Penn Engineering, Chris Murphy

Using EJS in an Express app

• Set EJS as the default rendering method in your app with app.set('view engine', 'ejs');

var express = require(‘express’);

var app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {

res.render('welcome', {username: 'CandyLover'});

});

SD4x-4.5 281

Property of Penn Engineering, Chris Murphy

Using EJS in an Express app

• Set EJS as the default rendering method in your app with app.set('view engine', 'ejs');

var express = require(‘express’);

var app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {

res.render('welcome', {username: 'CandyLover'});

});

SD4x-4.5 282

Property of Penn Engineering, Chris Murphy

Using EJS in an Express app

• Set EJS as the default rendering method in your app with app.set('view engine', 'ejs');

• Then generate and send the HTML from an .ejs file using the Response’s render function

var express = require(‘express’);

var app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {

res.render('welcome', {username: 'CandyLover'});

});

SD4x-4.5 283

Property of Penn Engineering, Chris Murphy

Using EJS in an Express app

• Set EJS as the default rendering method in your app with app.set('view engine', 'ejs');

• Then generate and send the HTML from an .ejs file using the Response’s render function

• Arguments to the .ejs file are passed as objects

var express = require(‘express’);

var app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {

res.render('welcome', {username: 'CandyLover'});

});

SD4x-4.5 284

Property of Penn Engineering, Chris Murphy

Writing EJS files

• A .ejs file is just an HTML file that has JavaScript code embedded in it

• Anything between <%= and %> tags will be evaluated and incorporated into the HTML

• By default, the .ejs files should be in the views/ subdirectory of the Express project

<!-- This is views/welcome.ejs -->

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

</body>

</html>SD4x-4.5 285

Property of Penn Engineering, Chris Murphy

Writing EJS files

• A .ejs file is just an HTML file that has JavaScript code embedded in it

• Anything between <%= and %> tags will be evaluated and incorporated into the HTML

• By default, the .ejs files should be in the views/ subdirectory of the Express project

<!-- This is views/welcome.ejs -->

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

</body>

</html>SD4x-4.5 286

Property of Penn Engineering, Chris Murphy

Writing EJS files

• A .ejs file is just an HTML file that has JavaScript code embedded in it

• Anything between <%= and %> tags will be evaluated and incorporated into the HTML

• By default, the .ejs files should be in the views/ subdirectory of the Express project

<!-- This is views/welcome.ejs -->

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

</body>

</html>SD4x-4.5 287

Property of Penn Engineering, Chris Murphy

Writing EJS files

• A .ejs file is just an HTML file that has JavaScript code embedded in it

• Anything between <%= and %> tags will be evaluated and incorporated into the HTML

• By default, the .ejs files should be in the views/ subdirectory of the Express project

<!-- This is views/welcome.ejs -->

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

</body>

</html>SD4x-4.5 288

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 289

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 290

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 291

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 292

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 293

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 294

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 295

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 296

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 297

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 298

Property of Penn Engineering, Chris Murphy

EJS and JavaScript

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

<!DOCTYPE html>

<html>

<body>

<h1>Welcome, <%= username %>!</h1>

<% if (isAdmin) { %>

<p> Remember to check your email every 24 hours! </p>

<% } %>

</body>

</html>

res.render('welcome', {username: 'CandyLover', isAdmin: true});

SD4x-4.5 299

Property of Penn Engineering, Chris Murphy SD4x-4.5 300

Property of Penn Engineering, Chris Murphy SD4x-4.5 301

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 302

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.type('html').status(200);

res.write('Hello, ' + name + ', nice to meet you.');

res.write('<p>Here are the animals you like:');

res.write('<ul>');

animals.forEach( (animal) => {

res.write('<li>' + animal + '</li>');

});

res.write('</ul>');

res.write("<a href='/public/form.html'>" +

"Back to form</a>");

res.end();

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 303

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 304

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 305

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 306

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 307

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 308

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 309

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

Property of Penn Engineering, Chris Murphy SD4x-4.5 310

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 311

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 312

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 313

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 314

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 315

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 316

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 317

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 318

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 319

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 320

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 321

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 322

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy SD4x-4.5 323

app.use('/handleForm', (req, res) => {

var name = req.body.username;

var animals = [].concat(req.body.animal);

res.render('showAnimals', { name: name,

animals: animals });

});

<!-- This is views/showAnimals.ejs -->

Hello, <%= name %>, nice to meet you.

<p>Here are the animals you like:

<ul>

<% animals.forEach( (animal) => { %>

<li> <%= animal %> </li>

<% }); %>

</ul>

<a href='/public/form.html'>Back to form</a>

Property of Penn Engineering, Chris Murphy

Summary

• EJS allows webpages to be developed statically and rendered dynamically server-side

• An Express app can generate and send the HTML from a .ejs file using the Response’s renderfunction

• EJS will execute any JavaScript that appears between <% and %> tags when generating the HTML page on the server

SD4x-4.5 324

Video 4.6

MongoDB: Setup and Insert

Chris Murphy

SD4x-4.6 325

Property of Penn Engineering, Chris Murphy

Review

• Node.js and Express allow us to build server-side web apps in JavaScript

• We can get data from the user via the URL query parameters or from form data

SD4x-4.6 326

Property of Penn Engineering, Chris Murphy SD4x-4.6 327

Client Server

Property of Penn Engineering, Chris Murphy SD4x-4.6 328

Client Server Database

Property of Penn Engineering, Chris Murphy

What is a NoSQL Database?

• A NoSQL Database is a database that does not use SQL, the traditional method of storing data

• In SQL, data is stored in tables and rows. This is also known as a relational database

• NoSQL Databases attempt to address some of the shortcomings of SQL and other relational databases by organizing and storing data differently

SD4x-4.6 329

Property of Penn Engineering, Chris Murphy

What is MongoDB?

• MongoDB is one NoSQL Database that is designed for use with JavaScript apps

• MongoDB stores collections of documents rather than tables of rows

SD4x-4.6 330

Property of Penn Engineering, Chris Murphy

SQL Database

• A SQL table of Users might look like this:

Name Age Country Occupation

Jane Doe 30 United States Programmer

John Smith 25 Canada Doctor

Kim Jones 27 France Painter

SD4x-4.6 331

Property of Penn Engineering, Chris Murphy

MongoDB Documents

• A MongoDB collection of User documents might look like this:

{

name: 'Jane Doe',

age: 30,

country: 'United States',

occupation: 'Programmer'

}

{

name: 'John Smith',

age: 25,

country: 'Canada',

occupation: 'Doctor'

}

{

name: 'Kim Jones',

age: 27,

country: 'France',

occupation: 'Painter'

}

SD4x-4.6 332

Property of Penn Engineering, Chris Murphy

Using MongoDB with a Node.js app

1. Install MongoDB locally or create an account on a remote service

2. Install packages locally to allow your JavaScript programs to access your MongoDB instance

3. Write JavaScript to describe the Schema (blueprint for Documents) that you will use in the Collection

4. Use the Schema to access MongoDB in your app

SD4x-4.6 333

Property of Penn Engineering, Chris Murphy

Installing MongoDB

• You can find download/installation instructions for MongoDB at https://mongodb.com/download

• Follow these instructions to create a new empty database and run the MongoDB server

• When you start it, it will tell you which port it is using

SD4x-4.6 334

Property of Penn Engineering, Chris Murphy SD4x-4.6 335

Property of Penn Engineering, Chris Murphy SD4x-4.6 336

Property of Penn Engineering, Chris Murphy SD4x-4.6 337

Property of Penn Engineering, Chris Murphy

Installing MongoDB

• You can find download/installation instructions for MongoDB at https://mongodb.com/download

• Follow these instructions to create a new empty database and run the MongoDB server

• When you start it, it will tell you which port it is using

SD4x-4.6 338

Property of Penn Engineering, Chris Murphy

Installing MongoDB

• You can find download/installation instructions for MongoDB at https://mongodb.com/download

• Follow these instructions to create a new empty database and run the MongoDB server

• When you start it, it will tell you which port it is using

• Alternatively, you may use an online service, e.g. MongoDB Atlas

SD4x-4.6 339

Property of Penn Engineering, Chris Murphy

Installing Drivers for MongoDB

• You can access MongoDB directly from your Node app using the MongoClient

• Alternatively, you can install helper packages such as Mongoose to simplify some tasks:

npm install mongoose --save

SD4x-4.6 340

Property of Penn Engineering, Chris Murphy SD4x-4.6 341

Property of Penn Engineering, Chris Murphy SD4x-4.6 342

<html>

<body>

<form action='/create' method='post'>

Name: <input name='name'>

<p>

Age: <input name='age'>

<p>

<input type=submit value='Submit form!'>

</form>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.6 343

<html>

<body>

<form action='/create' method='post'>

Name: <input name='name'>

<p>

Age: <input name='age'>

<p>

<input type=submit value='Submit form!'>

</form>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.6 344

<html>

<body>

<form action='/create' method='post'>

Name: <input name='name'>

<p>

Age: <input name='age'>

<p>

<input type=submit value='Submit form!'>

</form>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.6 345

<html>

<body>

<form action='/create' method='post'>

Name: <input name='name'>

<p>

Age: <input name='age'>

<p>

<input type=submit value='Submit form!'>

</form>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.6 346

<html>

<body>

<form action='/create' method='post'>

Name: <input name='name'>

<p>

Age: <input name='age'>

<p>

<input type=submit value='Submit form!'>

</form>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.6 347

<html>

<body>

<form action='/create' method='post'>

Name: <input name='name'>

<p>

Age: <input name='age'>

<p>

<input type=submit value='Submit form!'>

</form>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.6 348

<html>

<body>

<form action='/create' method='post'>

Name: <input name='name'>

<p>

Age: <input name='age'>

<p>

<input type=submit value='Submit form!'>

</form>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.6 349

Property of Penn Engineering, Chris Murphy SD4x-4.6 350

Property of Penn Engineering, Chris Murphy SD4x-4.6 351

Property of Penn Engineering, Chris Murphy SD4x-4.6 352

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 353

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 354

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 355

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 356

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 357

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 358

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 359

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 360

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 361

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 362

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 363

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 364

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 365

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 366

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 367

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 368

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 369

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 370

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 371

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 372

Property of Penn Engineering, Chris Murphy SD4x-4.6 373

/* This is index.js */

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Person = require('./Person.js');

. . .

// this is at the bottom

app.use('/public', express.static('public'));

app.use('/', (req, res) =>

{ res.redirect('/public/personform.html'); } );

app.listen(3000, () =>

{ console.log('Listening on port 3000'); } );

Property of Penn Engineering, Chris Murphy SD4x-4.6 374

/* This is index.js */

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Person = require('./Person.js');

. . .

// this is at the bottom

app.use('/public', express.static('public'));

app.use('/', (req, res) =>

{ res.redirect('/public/personform.html'); } );

app.listen(3000, () =>

{ console.log('Listening on port 3000'); } );

Property of Penn Engineering, Chris Murphy SD4x-4.6 375

/* This is index.js */

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Person = require('./Person.js');

. . .

// this is at the bottom

app.use('/public', express.static('public'));

app.use('/', (req, res) =>

{ res.redirect('/public/personform.html'); } );

app.listen(3000, () =>

{ console.log('Listening on port 3000'); } );

Property of Penn Engineering, Chris Murphy SD4x-4.6 376

/* This is index.js */

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Person = require('./Person.js');

. . .

// this is at the bottom

app.use('/public', express.static('public'));

app.use('/', (req, res) =>

{ res.redirect('/public/personform.html'); } );

app.listen(3000, () =>

{ console.log('Listening on port 3000'); } );

Property of Penn Engineering, Chris Murphy SD4x-4.6 377

/* This is index.js */

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Person = require('./Person.js');

. . .

// this is at the bottom

app.use('/public', express.static('public'));

app.use('/', (req, res) =>

{ res.redirect('/public/personform.html'); } );

app.listen(3000, () =>

{ console.log('Listening on port 3000'); } );

Property of Penn Engineering, Chris Murphy SD4x-4.6 378

/* This is index.js */

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Person = require('./Person.js');

. . .

// this is at the bottom

app.use('/public', express.static('public'));

app.use('/', (req, res) =>

{ res.redirect('/public/personform.html'); } );

app.listen(3000, () =>

{ console.log('Listening on port 3000'); } );

Property of Penn Engineering, Chris Murphy SD4x-4.6 379

/* This is index.js */

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Person = require('./Person.js');

. . .

// this is at the bottom

app.use('/public', express.static('public'));

app.use('/', (req, res) =>

{ res.redirect('/public/personform.html'); } );

app.listen(3000, () =>

{ console.log('Listening on port 3000'); } );

Property of Penn Engineering, Chris Murphy SD4x-4.6 380

/* This is index.js */

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Person = require('./Person.js');

. . .

// this is at the bottom

app.use('/public', express.static('public'));

app.use('/', (req, res) =>

{ res.redirect('/public/personform.html'); } );

app.listen(3000, () =>

{ console.log('Listening on port 3000'); } );

Property of Penn Engineering, Chris Murphy SD4x-4.6 381

Property of Penn Engineering, Chris Murphy SD4x-4.6 382

Property of Penn Engineering, Chris Murphy SD4x-4.6 383

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 384

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 385

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 386

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 387

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 388

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 389

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 390

<html>

<body>

<form action='/create' method='post'>

Name: <input name='name'>

<p>

Age: <input name='age'>

<p>

<input type=submit value='Submit form!'>

</form>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.6 391

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 392

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 393

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 394

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 395

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 396

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 397

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 398

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 399

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 400

app.use('/create', (req, res) => {

var newPerson = new Person ({ // defined in Person.js

name: req.body.name,

age: req.body.age,

});

newPerson.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { person: newPerson });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 401

<!-- This is views/created.ejs -->

Successfully created new person:

<p>

<b>Name:</b> <%= person.name %>

<br>

<b>Age:</b> <%= person.age %>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.6 402

<!-- This is views/created.ejs -->

Successfully created new person:

<p>

<b>Name:</b> <%= person.name %>

<br>

<b>Age:</b> <%= person.age %>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.6 403

<!-- This is views/created.ejs -->

Successfully created new person:

<p>

<b>Name:</b> <%= person.name %>

<br>

<b>Age:</b> <%= person.age %>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.6 404

<!-- This is views/created.ejs -->

Successfully created new person:

<p>

<b>Name:</b> <%= person.name %>

<br>

<b>Age:</b> <%= person.age %>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.6 405

Property of Penn Engineering, Chris Murphy SD4x-4.6 406

Property of Penn Engineering, Chris Murphy SD4x-4.6 407

Property of Penn Engineering, Chris Murphy SD4x-4.6 408

Property of Penn Engineering, Chris Murphy SD4x-4.6 409

Property of Penn Engineering, Chris Murphy SD4x-4.6 410

Property of Penn Engineering, Chris Murphy

Summary

• MongoDB is a NoSQL Database that is designed for use with JavaScript apps

• MongoDB stores collections of documents

• We can access MongoDB from our Node/Express app using libraries such as Mongoose

• We define a Schema and then can create new documents using the save function

SD4x-4.6 411

Video 4.7

MongoDB: Select and Update

Chris Murphy

SD4x-4.7 412

Property of Penn Engineering, Chris Murphy

Review

• MongoDB is a NoSQL Database that is designed for use with JavaScript apps

• MongoDB stores collections of documents

• We can access MongoDB from our Node/Express app using libraries such as Mongoose

• We define a Schema and then can create new documents using the save function

SD4x-4.7 413

Property of Penn Engineering, Chris Murphy SD4x-4.7 414

Client Server Database

Property of Penn Engineering, Chris Murphy SD4x-4.7 415

Property of Penn Engineering, Chris Murphy SD4x-4.7 416

Property of Penn Engineering, Chris Murphy SD4x-4.7 417

Property of Penn Engineering, Chris Murphy SD4x-4.7 418

Property of Penn Engineering, Chris Murphy SD4x-4.7 419

Property of Penn Engineering, Chris Murphy SD4x-4.7 420

Property of Penn Engineering, Chris Murphy SD4x-4.7 421

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 422

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 423

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.6 424

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 425

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.6 426

/* This is Person.js */

var mongoose = require('mongoose');

// note: your host/port number may be different!

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var personSchema = new Schema( {

name: {type: String, required: true, unique: true},

age: Number

} );

module.exports = mongoose.model('Person', personSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.7 427

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 428

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 429

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 430

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 431

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 432

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 433

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 434

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 435

app.use('/all', (req, res) => {

Person.find( (err, allPeople) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (allPeople.length == 0) {

res.type('html').status(200);

res.send('There are no people');

}

else {

res.render('showAll', { people: allPeople });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 436

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 437

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 438

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 439

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 440

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 441

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 442

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 443

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 444

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 445

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 446

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 447

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 448

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 449

<!-- This is views/showAll.ejs -->

Here are all the people:

<ul>

<% people.forEach( (person) => { %>

<li><a href="/person?name=<%= person.name %>">

<%= person.name %></a>:

<%= person.age %>

</li>

<% }); %>

</ul>

<br><a href='/public/personform.html'>Create New Person</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 450

Property of Penn Engineering, Chris Murphy SD4x-4.7 451

Property of Penn Engineering, Chris Murphy SD4x-4.7 452

Property of Penn Engineering, Chris Murphy SD4x-4.7 453

Property of Penn Engineering, Chris Murphy SD4x-4.7 454

Property of Penn Engineering, Chris Murphy SD4x-4.7 455

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 456

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 457

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 458

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 459

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 460

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 461

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 462

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 463

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 464

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 465

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 466

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 467

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 468

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 469

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 470

app.use('/person', (req, res) => {

var searchName = req.query.name;

Person.findOne( { name: searchName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + searchName);

}

else {

res.render('personInfo', { person : person });

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 471

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 472

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 473

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 474

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 475

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 476

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 477

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 478

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 479

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 480

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 481

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 482

<!-- This is views/personInfo.ejs -->

<form action='/update' method='post'>

Name: <%= person.name %><br>

<input name='username' value='<%= person.name %>' hidden>

Age: <input name='age' value='<%= person.age %>'>

<input type='submit' value='Update'>

</form>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 483

Property of Penn Engineering, Chris Murphy SD4x-4.7 484

Property of Penn Engineering, Chris Murphy SD4x-4.7 485

Property of Penn Engineering, Chris Murphy SD4x-4.7 486

Property of Penn Engineering, Chris Murphy SD4x-4.7 487

Property of Penn Engineering, Chris Murphy SD4x-4.7 488

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 489

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 490

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 491

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 492

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 493

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 494

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 495

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 496

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 497

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 498

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 499

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 500

app.use('/update', (req, res) => {

var updateName = req.body.username;

Person.findOne( { name: updateName }, (err, person) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else if (!person) {

res.type('html').status(200);

res.send('No person named ' + updateName);

}

else {

person.age = req.body.age;

person.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('updated', { person: person });

}

});

}

});

});

Property of Penn Engineering, Chris Murphy SD4x-4.7 501

<!-- This is views/updated.ejs -->

Updated <%= person.name %>'s age to <%= person.age %>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 502

<!-- This is views/updated.ejs -->

Updated <%= person.name %>'s age to <%= person.age %>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 503

<!-- This is views/updated.ejs -->

Updated <%= person.name %>'s age to <%= person.age %>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy SD4x-4.7 504

<!-- This is views/updated.ejs -->

Updated <%= person.name %>'s age to <%= person.age %>

<br><a href='/public/personform.html'>Create New Person</a>

<br><a href='/all'>Show All</a>

Property of Penn Engineering, Chris Murphy

Summary

• We can access MongoDB from our Node/Express app using libraries such as Mongoose

• We can use the find function to select all documents in a collection, or pass a query object to select only certain ones

• Once we have a document, we can update it using the save function

SD4x-4.7 505

Video 4.8

MongoDB: Advanced Queries

Chris Murphy

SD4x-4.8 506

Property of Penn Engineering, Chris Murphy

Review

• MongoDB is a NoSQL Database that stores collections of documents

• Once we’ve defined a Schema we can use the find function to select all documents in a collection, or pass a query object to select only certain ones

• Once we have a document, we can update it using the save function

SD4x-4.8 507

Property of Penn Engineering, Chris Murphy SD4x-4.8 508

{

title: 'Introduction to Algorithms',

year: 1990,

authors: [

{ name: 'Thomas Cormen', affiliation: 'Dartmouth' },

{ name: 'Charles Leiserson', affiliation: 'MIT' },

{ name: 'Ronald Rivest', affiliation: 'MIT' },

{ name: 'Clifford Stein', affiliation: 'Columbia' }

]

}

{

title: 'Principles of Compiler Design',

year: 1977,

authors: [

{ name: 'Alfred Aho', affiliation: 'Bell Labs' },

{ name: 'Jeffrey Ullman', affiliation: 'Princeton' }

]

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 509

{

title: 'Introduction to Algorithms',

year: 1990,

authors: [

{ name: 'Thomas Cormen', affiliation: 'Dartmouth' },

{ name: 'Charles Leiserson', affiliation: 'MIT' },

{ name: 'Ronald Rivest', affiliation: 'MIT' },

{ name: 'Clifford Stein', affiliation: 'Columbia' }

]

}

{

title: 'Principles of Compiler Design',

year: 1977,

authors: [

{ name: 'Alfred Aho', affiliation: 'Bell Labs' },

{ name: 'Jeffrey Ullman', affiliation: 'Princeton' }

]

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 510

{

title: 'Introduction to Algorithms',

year: 1990,

authors: [

{ name: 'Thomas Cormen', affiliation: 'Dartmouth' },

{ name: 'Charles Leiserson', affiliation: 'MIT' },

{ name: 'Ronald Rivest', affiliation: 'MIT' },

{ name: 'Clifford Stein', affiliation: 'Columbia' }

]

}

{

title: 'Principles of Compiler Design',

year: 1977,

authors: [

{ name: 'Alfred Aho', affiliation: 'Bell Labs' },

{ name: 'Jeffrey Ullman', affiliation: 'Princeton' }

]

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 511

{

title: 'Introduction to Algorithms',

year: 1990,

authors: [

{ name: 'Thomas Cormen', affiliation: 'Dartmouth' },

{ name: 'Charles Leiserson', affiliation: 'MIT' },

{ name: 'Ronald Rivest', affiliation: 'MIT' },

{ name: 'Clifford Stein', affiliation: 'Columbia' }

]

}

{

title: 'Principles of Compiler Design',

year: 1977,

authors: [

{ name: 'Alfred Aho', affiliation: 'Bell Labs' },

{ name: 'Jeffrey Ullman', affiliation: 'Princeton' }

]

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 512

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 513

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 514

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 515

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 516

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 517

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 518

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 519

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 520

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 521

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 522

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 523

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 524

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 525

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 526

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase');

var Schema = mongoose.Schema;

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

module.exports = mongoose.model('Book', bookSchema);

Property of Penn Engineering, Chris Murphy SD4x-4.8 527

Property of Penn Engineering, Chris Murphy SD4x-4.8 528

<form action='/createbook' method='post'>

Title: <input name='title'>

<p>

Year: <input name='year'>

<p>

Author #1: <br>

Name: <input name='authors[0][name]'> <br>

Affiliation: <input name='authors[0][affiliation]'>

<p>

Author #2: <br>

Name: <input name='authors[1][name]'> <br>

Affiliation: <input name='authors[1][affiliation]'>

<p>

<input type='submit' value='Submit'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 529

<form action='/createbook' method='post'>

Title: <input name='title'>

<p>

Year: <input name='year'>

<p>

Author #1: <br>

Name: <input name='authors[0][name]'> <br>

Affiliation: <input name='authors[0][affiliation]'>

<p>

Author #2: <br>

Name: <input name='authors[1][name]'> <br>

Affiliation: <input name='authors[1][affiliation]'>

<p>

<input type='submit' value='Submit'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 530

<form action='/createbook' method='post'>

Title: <input name='title'>

<p>

Year: <input name='year'>

<p>

Author #1: <br>

Name: <input name='authors[0][name]'> <br>

Affiliation: <input name='authors[0][affiliation]'>

<p>

Author #2: <br>

Name: <input name='authors[1][name]'> <br>

Affiliation: <input name='authors[1][affiliation]'>

<p>

<input type='submit' value='Submit'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 531

<form action='/createbook' method='post'>

Title: <input name='title'>

<p>

Year: <input name='year'>

<p>

Author #1: <br>

Name: <input name='authors[0][name]'> <br>

Affiliation: <input name='authors[0][affiliation]'>

<p>

Author #2: <br>

Name: <input name='authors[1][name]'> <br>

Affiliation: <input name='authors[1][affiliation]'>

<p>

<input type='submit' value='Submit'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 532

<form action='/createbook' method='post'>

Title: <input name='title'>

<p>

Year: <input name='year'>

<p>

Author #1: <br>

Name: <input name='authors[0][name]'> <br>

Affiliation: <input name='authors[0][affiliation]'>

<p>

Author #2: <br>

Name: <input name='authors[1][name]'> <br>

Affiliation: <input name='authors[1][affiliation]'>

<p>

<input type='submit' value='Submit'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 533

<form action='/createbook' method='post'>

Title: <input name='title'>

<p>

Year: <input name='year'>

<p>

Author #1: <br>

Name: <input name='authors[0][name]'> <br>

Affiliation: <input name='authors[0][affiliation]'>

<p>

Author #2: <br>

Name: <input name='authors[1][name]'> <br>

Affiliation: <input name='authors[1][affiliation]'>

<p>

<input type='submit' value='Submit'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 534

<form action='/createbook' method='post'>

Title: <input name='title'>

<p>

Year: <input name='year'>

<p>

Author #1: <br>

Name: <input name='authors[0][name]'> <br>

Affiliation: <input name='authors[0][affiliation]'>

<p>

Author #2: <br>

Name: <input name='authors[1][name]'> <br>

Affiliation: <input name='authors[1][affiliation]'>

<p>

<input type='submit' value='Submit'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 535

<form action='/createbook' method='post'>

Title: <input name='title'>

<p>

Year: <input name='year'>

<p>

Author #1: <br>

Name: <input name='authors[0][name]'> <br>

Affiliation: <input name='authors[0][affiliation]'>

<p>

Author #2: <br>

Name: <input name='authors[1][name]'> <br>

Affiliation: <input name='authors[1][affiliation]'>

<p>

<input type='submit' value='Submit'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 536

<form action='/createbook' method='post'>

Title: <input name='title'>

<p>

Year: <input name='year'>

<p>

Author #1: <br>

Name: <input name='authors[0][name]'> <br>

Affiliation: <input name='authors[0][affiliation]'>

<p>

Author #2: <br>

Name: <input name='authors[1][name]'> <br>

Affiliation: <input name='authors[1][affiliation]'>

<p>

<input type='submit' value='Submit'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 537

Property of Penn Engineering, Chris Murphy SD4x-4.8 538

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 539

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 540

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 541

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 542

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 543

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 544

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 545

{ title: 'JavaScript Programming',

year: '2017',

authors:

[ { name: 'Chris Murphy', affiliation: 'UPenn' },

{ name: 'Swapneel Sheth', affiliation: 'UPenn' } ] }

Property of Penn Engineering, Chris Murphy SD4x-4.8 546

{ title: 'JavaScript Programming',

year: '2017',

authors:

[ { name: 'Chris Murphy', affiliation: 'UPenn' },

{ name: 'Swapneel Sheth', affiliation: 'UPenn' } ] }

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 547

{ title: 'JavaScript Programming',

year: '2017',

authors:

[ { name: 'Chris Murphy', affiliation: 'UPenn' },

{ name: 'Swapneel Sheth', affiliation: 'UPenn' } ] }

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 548

{ title: 'JavaScript Programming',

year: '2017',

authors:

[ { name: 'Chris Murphy', affiliation: 'UPenn' },

{ name: 'Swapneel Sheth', affiliation: 'UPenn' } ] }

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 549

{ title: 'JavaScript Programming',

year: '2017',

authors:

[ { name: 'Chris Murphy', affiliation: 'UPenn' },

{ name: 'Swapneel Sheth', affiliation: 'UPenn' } ] }

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 550

{ title: 'JavaScript Programming',

year: '2017',

authors:

[ { name: 'Chris Murphy', affiliation: 'UPenn' },

{ name: 'Swapneel Sheth', affiliation: 'UPenn' } ] }

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 551

{ title: 'JavaScript Programming',

year: '2017',

authors:

[ { name: 'Chris Murphy', affiliation: 'UPenn' },

{ name: 'Swapneel Sheth', affiliation: 'UPenn' } ] }

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 552

{ title: 'JavaScript Programming',

year: '2017',

authors:

[ { name: 'Chris Murphy', affiliation: 'UPenn' },

{ name: 'Swapneel Sheth', affiliation: 'UPenn' } ] }

var authorSchema = new Schema({

name: String,

affiliation: String

});

var bookSchema = new Schema({

title: {type: String, required: true, unique: true},

year: Number,

authors: [authorSchema]

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 553

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 554

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 555

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 556

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/createbook', (req, res) => {

console.log(req.body);

var newBook = new Book(req.body);

newBook.save( (err) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('created', { book: newBook });

}

} );

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 557

Property of Penn Engineering, Chris Murphy SD4x-4.8 558

Indicate the search criteria:

<form action='/search' method='post'>

Title: <input name='title'>

<p>

Author name: <input name='name'>

<p>

Year: <input name='year'>

<p>

<input type='radio' name='which' value='all' checked>All

<br>

<input type='radio' name='which' value='any'>Any

<p>

<input type='submit' value='Search'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 559

Indicate the search criteria:

<form action='/search' method='post'>

Title: <input name='title'>

<p>

Author name: <input name='name'>

<p>

Year: <input name='year'>

<p>

<input type='radio' name='which' value='all' checked>All

<br>

<input type='radio' name='which' value='any'>Any

<p>

<input type='submit' value='Search'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 560

Indicate the search criteria:

<form action='/search' method='post'>

Title: <input name='title'>

<p>

Author name: <input name='name'>

<p>

Year: <input name='year'>

<p>

<input type='radio' name='which' value='all' checked>All

<br>

<input type='radio' name='which' value='any'>Any

<p>

<input type='submit' value='Search'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 561

Indicate the search criteria:

<form action='/search' method='post'>

Title: <input name='title'>

<p>

Author name: <input name='name'>

<p>

Year: <input name='year'>

<p>

<input type='radio' name='which' value='all' checked>All

<br>

<input type='radio' name='which' value='any'>Any

<p>

<input type='submit' value='Search'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 562

Indicate the search criteria:

<form action='/search' method='post'>

Title: <input name='title'>

<p>

Author name: <input name='name'>

<p>

Year: <input name='year'>

<p>

<input type='radio' name='which' value='all' checked>All

<br>

<input type='radio' name='which' value='any'>Any

<p>

<input type='submit' value='Search'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 563

Indicate the search criteria:

<form action='/search' method='post'>

Title: <input name='title'>

<p>

Author name: <input name='name'>

<p>

Year: <input name='year'>

<p>

<input type='radio' name='which' value='all' checked>All

<br>

<input type='radio' name='which' value='any'>Any

<p>

<input type='submit' value='Search'>

</form>

Property of Penn Engineering, Chris Murphy SD4x-4.8 564

Property of Penn Engineering, Chris Murphy SD4x-4.8 565

app.use('/search', (req, res) => {

if (req.body.which == 'all') {

searchAll(req, res);

}

else if (req.body.which == 'any') {

searchAny(req, res);

}

else {

searchAll(req, res);

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 566

app.use('/search', (req, res) => {

if (req.body.which == 'all') {

searchAll(req, res);

}

else if (req.body.which == 'any') {

searchAny(req, res);

}

else {

searchAll(req, res);

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 567

app.use('/search', (req, res) => {

if (req.body.which == 'all') {

searchAll(req, res);

}

else if (req.body.which == 'any') {

searchAny(req, res);

}

else {

searchAll(req, res);

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 568

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 569

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 570

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 571

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 572

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 573

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 574

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 575

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 576

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 577

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 578

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

// { 'authors.name': 'Chris Murphy', year: '2017' }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 579

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

// { 'authors.name': 'Chris Murphy', year: '2017' }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 580

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

// { 'authors.name': 'Chris Murphy', year: '2017' }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 581

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

// { 'authors.name': 'Chris Murphy', year: '2017' }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 582

Property of Penn Engineering, Chris Murphy SD4x-4.8 583

<!-- This is views/books.ejs -->

Here are the results of your search:

<ul>

<% books.forEach( (book) => { %>

<li>

<i><%= book.title %></i>.

<% book.authors.forEach( (author) => { %>

<%= author.name %>,

<% }); %>

<%= book.year %>.

</li>

<% }); %>

</ul>

Property of Penn Engineering, Chris Murphy SD4x-4.8 584

<!-- This is views/books.ejs -->

Here are the results of your search:

<ul>

<% books.forEach( (book) => { %>

<li>

<i><%= book.title %></i>.

<% book.authors.forEach( (author) => { %>

<%= author.name %>,

<% }); %>

<%= book.year %>.

</li>

<% }); %>

</ul>

Property of Penn Engineering, Chris Murphy SD4x-4.8 585

<!-- This is views/books.ejs -->

Here are the results of your search:

<ul>

<% books.forEach( (book) => { %>

<li>

<i><%= book.title %></i>.

<% book.authors.forEach( (author) => { %>

<%= author.name %>,

<% }); %>

<%= book.year %>.

</li>

<% }); %>

</ul>

Property of Penn Engineering, Chris Murphy SD4x-4.8 586

<!-- This is views/books.ejs -->

Here are the results of your search:

<ul>

<% books.forEach( (book) => { %>

<li>

<i><%= book.title %></i>.

<% book.authors.forEach( (author) => { %>

<%= author.name %>,

<% }); %>

<%= book.year %>.

</li>

<% }); %>

</ul>

Property of Penn Engineering, Chris Murphy SD4x-4.8 587

<!-- This is views/books.ejs -->

Here are the results of your search:

<ul>

<% books.forEach( (book) => { %>

<li>

<i><%= book.title %></i>.

<% book.authors.forEach( (author) => { %>

<%= author.name %>,

<% }); %>

<%= book.year %>.

</li>

<% }); %>

</ul>

Property of Penn Engineering, Chris Murphy SD4x-4.8 588

<!-- This is views/books.ejs -->

Here are the results of your search:

<ul>

<% books.forEach( (book) => { %>

<li>

<i><%= book.title %></i>.

<% book.authors.forEach( (author) => { %>

<%= author.name %>,

<% }); %>

<%= book.year %>.

</li>

<% }); %>

</ul>

Property of Penn Engineering, Chris Murphy SD4x-4.8 589

<!-- This is views/books.ejs -->

Here are the results of your search:

<ul>

<% books.forEach( (book) => { %>

<li>

<i><%= book.title %></i>.

<% book.authors.forEach( (author) => { %>

<%= author.name %>,

<% }); %>

<%= book.year %>.

</li>

<% }); %>

</ul>

Property of Penn Engineering, Chris Murphy SD4x-4.8 590

<!-- This is views/books.ejs -->

Here are the results of your search:

<ul>

<% books.forEach( (book) => { %>

<li>

<i><%= book.title %></i>.

<% book.authors.forEach( (author) => { %>

<%= author.name %>,

<% }); %>

<%= book.year %>.

</li>

<% }); %>

</ul>

Property of Penn Engineering, Chris Murphy SD4x-4.8 591

<!-- This is views/books.ejs -->

Here are the results of your search:

<ul>

<% books.forEach( (book) => { %>

<li>

<i><%= book.title %></i>.

<% book.authors.forEach( (author) => { %>

<%= author.name %>,

<% }); %>

<%= book.year %>.

</li>

<% }); %>

</ul>

Property of Penn Engineering, Chris Murphy SD4x-4.8 592

Property of Penn Engineering, Chris Murphy SD4x-4.8 593

app.use('/search', (req, res) => {

if (req.body.which == 'all') {

searchAll(req, res);

}

else if (req.body.which == 'any') {

searchAny(req, res);

}

else {

searchAll(req, res);

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 594

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 595

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 596

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 597

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 598

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 599

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 600

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 601

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 602

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 603

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 604

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 605

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 606

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 607

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 608

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

// { '$or': [ {title: 'Programming'}, {year: '2017'} ] }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 609

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year)

terms.push( { year: req.body.year });

if (req.body.name)

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.8 610

Property of Penn Engineering, Chris Murphy SD4x-4.8 611

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year) {

terms.push( { year: req.body.year });

if (req.body.name) {

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

// { '$or': [ {title: 'Programming'}, {year: '2017'} ] }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 612

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year) {

terms.push( { year: req.body.year });

if (req.body.name) {

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

// { '$or': [ {title: 'Programming'}, {year: '2017'} ] }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 613

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: req.body.title });

if (req.body.year) {

terms.push( { year: req.body.year });

if (req.body.name) {

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

// { '$or': [ {title: 'Programming'}, {year: '2017'} ] }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 614

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: { $regex: req.body.title } });

if (req.body.year) {

terms.push( { year: req.body.year });

if (req.body.name) {

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

// { '$or': [ {title: 'Programming'}, {year: '2017'} ] }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 615

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: { $regex: req.body.title } });

if (req.body.year) {

terms.push( { year: req.body.year });

if (req.body.name) {

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

// { '$or': [ {title: [Object]}, {year: '2017'} ] }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 616

Property of Penn Engineering, Chris Murphy SD4x-4.8 617

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: { $regex: req.body.title } });

if (req.body.year) {

terms.push( { year: req.body.year });

if (req.body.name) {

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

// { '$or': [ {title: [Object]}, {year: '2017'} ] }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

Property of Penn Engineering, Chris Murphy SD4x-4.8 618

function searchAny(req, res) {

var terms = [];

if (req.body.title)

terms.push( { title: { $regex: req.body.title } });

if (req.body.year) {

terms.push( { year: req.body.year });

if (req.body.name) {

terms.push( { 'authors.name' : req.body.name });

var query = { $or : terms };

console.log(query);

// { '$or': [ {title: [Object]}, {year: '2017'} ] }

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

}).sort( { 'title' : 'asc' } );

Property of Penn Engineering, Chris Murphy SD4x-4.8 619

Property of Penn Engineering, Chris Murphy

Summary

• MongoDB allows us to have a Schema in which one document contains other documents

• We can then do queries for documents using the properties of the documents they contain

• We can also do “all” and “any” queries by passing objects to the find function

• And sort the results using sort

SD4x-4.8 620

Video 4.9

Creating an API

Chris Murphy

SD4x-4.9 621

Property of Penn Engineering, Chris Murphy

Review

• Node.js and Express allow us to build server-side web apps in JavaScript

• MongoDB allows us to store data as documents and query them via JavaScript

SD4x-4.9 622

Property of Penn Engineering, Chris Murphy SD4x-4.9 623

Property of Penn Engineering, Chris Murphy SD4x-4.9 624

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.9 625

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.9 626

function searchAll(req, res) {

var query = {};

if (req.body.title) query.title = req.body.title;

if (req.body.year) query.year = req.body.year;

if (req.body.name) {

query['authors.name'] = req.body.name;

}

console.log(query);

Book.find( query, (err, books) => {

if (err) {

res.type('html').status(500);

res.send('Error: ' + err);

}

else {

res.render('books', { books: books });

}

});

}

Property of Penn Engineering, Chris Murphy SD4x-4.9 627

Property of Penn Engineering, Chris Murphy SD4x-4.9 628

Property of Penn Engineering, Chris Murphy SD4x-4.9 629

Property of Penn Engineering, Chris Murphy SD4x-4.9 630

Client Server Database

HTTP Request

HTTP Response

Entire HTML Page

Query

Results

Property of Penn Engineering, Chris Murphy SD4x-4.9 631

Client Server Database

HTTP Request

HTTP Response

Entire HTML Page

Query

Results

Property of Penn Engineering, Chris Murphy SD4x-4.9 632

Client Server Database

HTTP Request

HTTP Response

Just the Data!

Query

Results

Property of Penn Engineering, Chris Murphy

What is an API?

• An API is an Application Programming Interface

• It is a URL or a set of URLs that returns pure data to requests

• APIs can be used to incorporate data and functionality from other sources in your webapp

SD4x-4.9 633

Property of Penn Engineering, Chris Murphy

What is an API?

• An API is an Application Programming Interface

• It is a URL or a set of URLs that returns pure data to requests

• APIs can be used to incorporate data and functionality from other sources in your webapp

• You can also create your own API using Node.js to return JSON data to HTTP requests

SD4x-4.9 634

Property of Penn Engineering, Chris Murphy SD4x-4.9 635

GET /public/books.html

HTML

Property of Penn Engineering, Chris Murphy SD4x-4.9 636

Query

JSON

GET /api?...

GET /public/books.html

HTML

Result

Property of Penn Engineering, Chris Murphy SD4x-4.9 637

Result

Query

Query

JSON

GET /api?...

JSON

GET /api?...

GET /public/books.html

HTML

Result

Property of Penn Engineering, Chris Murphy SD4x-4.9 638

JSON

Result

Result

Query

Query

QueryGET /api?...

JSON

GET /api?...

JSON

GET /api?...

GET /public/books.html

HTML

Result

Property of Penn Engineering, Chris Murphy SD4x-4.9 639

Property of Penn Engineering, Chris Murphy SD4x-4.9 640

GET /public/books.html

HTML

Property of Penn Engineering, Chris Murphy SD4x-4.9 641

Property of Penn Engineering, Chris Murphy SD4x-4.9 642

Property of Penn Engineering, Chris Murphy SD4x-4.9 643

Query

JSON

GET /api?...

GET /public/books.html

HTML

Result

Property of Penn Engineering, Chris Murphy SD4x-4.9 644

Property of Penn Engineering, Chris Murphy SD4x-4.9 645

Property of Penn Engineering, Chris Murphy SD4x-4.9 646

Result

Query

Query

JSON

GET /api?...

JSON

GET /api?...

GET /public/books.html

HTML

Result

Property of Penn Engineering, Chris Murphy SD4x-4.9 647

Property of Penn Engineering, Chris Murphy SD4x-4.9 648

Property of Penn Engineering, Chris Murphy SD4x-4.9 649

Property of Penn Engineering, Chris Murphy SD4x-4.9 650

Property of Penn Engineering, Chris Murphy SD4x-4.9 651

Property of Penn Engineering, Chris Murphy SD4x-4.9 652

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/public', express.static('public'));

. . .

Property of Penn Engineering, Chris Murphy SD4x-4.9 653

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/public', express.static('public'));

. . .

Property of Penn Engineering, Chris Murphy SD4x-4.9 654

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/public', express.static('public'));

. . .

Property of Penn Engineering, Chris Murphy SD4x-4.9 655

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/public', express.static('public'));

. . .

Property of Penn Engineering, Chris Murphy SD4x-4.9 656

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/public', express.static('public'));

. . .

Property of Penn Engineering, Chris Murphy SD4x-4.9 657

var express = require('express');

var app = express();

app.set('view engine', 'ejs');

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

var Book = require('./Book.js');

app.use('/public', express.static('public'));

. . .

Property of Penn Engineering, Chris Murphy SD4x-4.9 658

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 659

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 660

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 661

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 662

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 663

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 664

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 665

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 666

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 667

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 668

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 669

[ { _id: 5967e069359c635bb106d662,

title: 'Intro to Java Programming',

year: 2017,

__v: 0,

authors: [ [Object] ]},

{ _id: 5967d3b75d1bcf5afa49ca3a,

title: 'JavaScript Programming',

year: 2017,

__v: 0,

authors: [ [Object], [Object] ] },

{ _id: 5967e095359c635bb106d665,

title: 'The Art of Computer Programming',

year: 1968,

__v: 0,

authors: [ [Object] ] } ]

Property of Penn Engineering, Chris Murphy SD4x-4.9 670

[ { _id: 5967e069359c635bb106d662,

title: 'Intro to Java Programming',

year: 2017,

__v: 0,

authors: [ [Object] ]},

{ _id: 5967d3b75d1bcf5afa49ca3a,

title: 'JavaScript Programming',

year: 2017,

__v: 0,

authors: [ [Object], [Object] ] },

{ _id: 5967e095359c635bb106d665,

title: 'The Art of Computer Programming',

year: 1968,

__v: 0,

authors: [ [Object] ] } ]

Property of Penn Engineering, Chris Murphy SD4x-4.9 671

[ { _id: 5967e069359c635bb106d662,

title: 'Intro to Java Programming',

year: 2017,

__v: 0,

authors: [ [Object] ]},

{ _id: 5967d3b75d1bcf5afa49ca3a,

title: 'JavaScript Programming',

year: 2017,

__v: 0,

authors: [ [Object], [Object] ] },

{ _id: 5967e095359c635bb106d665,

title: 'The Art of Computer Programming',

year: 1968,

__v: 0,

authors: [ [Object] ] } ]

Property of Penn Engineering, Chris Murphy SD4x-4.9 672

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 673

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 674

app.use( '/api', (req, res) => {

var query = {};

if (req.query.title)

query.title = { $regex : req.query.title };

if (req.query.name)

query['authors.name'] = { $regex: req.query.name };

if (req.query.year)

query.year = req.query.year;

if (Object.keys(query).length != 0) {

Book.find( query, (err, books) => {

if (!err)

res.json(books);

else {

console.log(err)

res.json({});

}

});

}

else res.json({}); // empty query

});

Property of Penn Engineering, Chris Murphy SD4x-4.9 675

Property of Penn Engineering, Chris Murphy SD4x-4.9 676

Property of Penn Engineering, Chris Murphy SD4x-4.9 677

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Book Finder</title>

<script src="jquery.js"></script>

</head>

<body>

<form>

Title: <input name='title'><br>

Author: <input name='author'><br>

Year: <input name='year'><br>

</form>

<ul>

<div id='results'></div>

</ul>

<script>

// next slide -->

</script>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.9 678

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Book Finder</title>

<script src="jquery.js"></script>

</head>

<body>

<form>

Title: <input name='title'><br>

Author: <input name='author'><br>

Year: <input name='year'><br>

</form>

<ul>

<div id='results'></div>

</ul>

<script>

// next slide -->

</script>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.9 679

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Book Finder</title>

<script src="jquery.js"></script>

</head>

<body>

<form>

Title: <input name='title'><br>

Author: <input name='author'><br>

Year: <input name='year'><br>

</form>

<ul>

<div id='results'></div>

</ul>

<script>

// next slide -->

</script>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.9 680

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Book Finder</title>

<script src="jquery.js"></script>

</head>

<body>

<form>

Title: <input name='title'><br>

Author: <input name='author'><br>

Year: <input name='year'><br>

</form>

<ul>

<div id='results'></div>

</ul>

<script>

// next slide -->

</script>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.9 681

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Book Finder</title>

<script src="jquery.js"></script>

</head>

<body>

<form>

Title: <input name='title'><br>

Author: <input name='author'><br>

Year: <input name='year'><br>

</form>

<ul>

<div id='results'></div>

</ul>

<script>

// next slide -->

</script>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.9 682

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Book Finder</title>

<script src="jquery.js"></script>

</head>

<body>

<form>

Title: <input name='title'><br>

Author: <input name='author'><br>

Year: <input name='year'><br>

</form>

<ul>

<div id='results'></div>

</ul>

<script>

// next slide -->

</script>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.9 683

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Book Finder</title>

<script src="jquery.js"></script>

</head>

<body>

<form>

Title: <input name='title'><br>

Author: <input name='author'><br>

Year: <input name='year'><br>

</form>

<ul>

<div id='results'></div>

</ul>

<script>

// next slide -->

</script>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.9 684

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 685

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 686

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 687

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 688

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 689

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 690

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 691

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 692

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 693

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 694

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 695

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 696

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 697

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 698

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 699

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 700

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 701

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 702

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Book Finder</title>

<script src="jquery.js"></script>

</head>

<body>

<form>

Title: <input name='title'><br>

Author: <input name='author'><br>

Year: <input name='year'><br>

</form>

<ul>

<div id='results'></div>

</ul>

<script>

// next slide -->

</script>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.9 703

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>Book Finder</title>

<script src="jquery.js"></script>

</head>

<body>

<form>

Title: <input name='title'><br>

Author: <input name='author'><br>

Year: <input name='year'><br>

</form>

<ul>

<div id='results'></div>

</ul>

<script>

// next slide -->

</script>

</body>

</html>

Property of Penn Engineering, Chris Murphy SD4x-4.9 704

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 705

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 706

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 707

[ { _id: 5967e069359c635bb106d662,

title: 'Intro to Java Programming',

year: 2017,

__v: 0,

authors: [ [Object] ]},

{ _id: 5967d3b75d1bcf5afa49ca3a,

title: 'JavaScript Programming',

year: 2017,

__v: 0,

authors: [ [Object], [Object] ] },

{ _id: 5967e095359c635bb106d665,

title: 'The Art of Computer Programming',

year: 1968,

__v: 0,

authors: [ [Object] ] } ]

Property of Penn Engineering, Chris Murphy SD4x-4.9 708

[ { _id: 5967e069359c635bb106d662,

title: 'Intro to Java Programming',

year: 2017,

__v: 0,

authors: [ [Object] ]},

{ _id: 5967d3b75d1bcf5afa49ca3a,

title: 'JavaScript Programming',

year: 2017,

__v: 0,

authors: [ [Object], [Object] ] },

{ _id: 5967e095359c635bb106d665,

title: 'The Art of Computer Programming',

year: 1968,

__v: 0,

authors: [ [Object] ] } ]

Property of Penn Engineering, Chris Murphy SD4x-4.9 709

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 710

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 711

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 712

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 713

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 714

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 715

<script>

$("input").on( "change input textInput", () => {

var title = $("input[name='title']").val();

var author = $("input[name='author']").val();

var year = $("input[name='year']").val();

var query = '?';

if (title) query += 'title=' + title + '&';

if (author) query += 'name=' + author + '&';

if (year) query += 'year=' + year;

var url = 'http://localhost:3000/api/' + query;

$.getJSON(url, (books, status) => {

var results = $("#results");

results.html('');

books.forEach( (book) => {

results.append('<li><i>' + book.title + '</i>, ');

book.authors.forEach( (author) => {

if (author.name) results.append(author.name + ', ');

});

results.append(book.year + '</li>');

});

});

});

</script>

Property of Penn Engineering, Chris Murphy SD4x-4.9 716

Property of Penn Engineering, Chris Murphy

Summary

• We can use server-side tools such as Node.js, Express, and MongoDB to develop APIs to make data available on the Web

• We can use client-side tools such as jQuery, React.js, and D3.js to access that data and display it in a Web page

SD4x-4.9 717