Web Development

lecture at DHBW Stuttgart

given by Johannes Kronmüller in September–October 2019

Johannes Kronmüller

Frontend Web Developer / IT-Consultant

  • Mercedes-Benz Bank AG Oct 2018–today
  • Steuerbot GmbH Oct 2017–Sep 2018
  • IBM iX Sep 2015–Aug 2017
  • lecturer in Web Development2019–today
  • lecturer in Open Source2019–today
  • M.Sc. IT-Management, FOM Hamburg 2015–2017
  • B.Sc. Information Systems, Uni Stuttgart 2012–2015
  • Professional Scrum Master (PSM I)
  • Enterprise Design Thinking Practitioner

Content Outline

  1. Web 101: Static Web Pages
  2. Frontend Development I: Interactive Web Pages
  3. Backend Development: Dynamic Data
  4. Frontend Development II: Frameworks
  5. Advanced Topics

Web 101: Static Web Pages

  1. Prelude
    1. Benefits of Becoming a Web Developer
    2. History of the World Wide Web
    3. State of the Web 2019
  2. Web Development Environment
  3. Basic Web Technology
    1. HTTP
    2. HTML
    3. CSS

Frontend Dev I: Interactive Web Pages

  1. JavaScript
    1. Characteristics & History
    2. Document Object Model (DOM)
    3. JSON
    4. Promises
    5. Fetch API

Backend Dev: Dynamic Data

  1. Server Side Web Technology
    1. Architecture Overview
    2. Web Frameworks
    3. Server Side JavaScript (NodeJS)
    4. Package Management
  2. Building an API
    1. REST
    2. Express JS
    3. OpenAPI Specification
  3. Excursion: JavaScript Fatigue

Frontend Dev II: Frameworks

  1. Single Page Applications
    1. Virtual DOM
    2. Client Side Routing
    3. Frontend Frameworks
  2. React
    1. Hello World
    2. JSX
    3. Components and Props
    4. Hooks: State and Effects

Advanced Topics

  • Authorization & Web Security
  • Rendering Strategies & Performance
  • Web Accessibility
  • Mobile Development
  • Web Components
  • Micro Frontends
  • Web Scraping
  • Internationalization (i18n)
  • Testing
  • Real Time Systems

Benefits of Becoming a Web Developer

https://youtu.be/JguKLogoGMk

The Pay

  • High paying jobs
  • Make money with side projects
  • Highest paying jobs without need of formal education

The industry isn't going anywhere

  • We will always need websites, web apps, web services...
  • Every industry benefits from web development
  • Don't worry about Wix taking your jobs

You can be self taught

  • Industry full of college dropouts
  • Having a portfolio is the most important thing to have
  • Learn for free

It isn't boring

  • Extremly satisfying to build things
  • Unleash your creativity
  • Not standardized and mind numbing
  • Always learn & do new things

Work for yourself

  • Freelancing / Consulting
  • Side projects for revenue stream
  • Content creation
  • Learn business skills

Work from anywhere

  • Most companies provide home office options
  • Running own company is easier than in most other professions
  • 100% remote work is a thing

Seeing Results

  • You build things that last (if you like it or not)
  • People use the applications you build
  • Build tools you can use in other areas of your life

History of the World Wide Web

Tim Berners-Lee, a British scientist, invented the World Wide Web (WWW) in 1989, while working at CERN.

1990

  • three fundamental technologies
    • HyperText Markup Language (HTML)
    • Uniform Resource Identifier (URI)
    • Hypertext Transfer Protocol (HTTP)
  • first web browser: WorldWideWeb
  • first web server: httpd

1991

world's first webpage

1993

NCSA Mosaic Browser

first browser able to render embedded elements like images

1994

World Wide Web Consortium (W3C)

The W3C’s vision was to standardize the protocols and technologies used to build the web such that the content would be available to as wide a population of the world as possible.

1995

Browser Wars

2000

Dot-Com Bubble

State of the Web 2019

  • request to allow notifications,
  • request to set as default homepage,
  • cookie consent,
  • age verification,
  • request to allow geolocation,
  • request to subscribe to newsletter,
  • support live chat,
  • adblocker notice,
  • satisfaction evaluation modal,
  • broken content and
  • request to like / share on social media

Obviously, this is annoying to customers actually interacting with the website…

how come those patterns are so common?

Web Development Environment

Code Editor: Visual Studio Code

Most Popular Development Environments (2019)

Browser Dev Tools: Chrome

Web Browser Usage Trends (Aug 2019)

Version Control: GitHub

The State of the Octoverse (2018)

Basic Web Technology

Hypertext Transfer Protocol

The Request/Response Cycle of the Web

Uniform Resource Identifiers (URIs)

URLs are a subset of URIs limited to the schemes http and https.

HTTP Request

  • a request line with method path and http version
    GET /images/logo.png HTTP/1.1
  • the host header
    Host: example.com
  • optional additional request headers
    Accept-Language: en
  • an empty line
  • an optional message body

HTTP Response

  • a status line with http version, status code and reason message
    HTTP/1.1 200 OK
  • optional response headers
    Content-Type: text/html
  • an empty line
  • an optional message body

HTTP Request & Response Example

Request


								GET / HTTP/1.1
								Host: www.example.com
					

Response


							HTTP/1.1 200 OK
							Date: Mon, 23 May 2005 22:38:34 GMT
							Content-Type: text/html; charset=UTF-8
							Content-Length: 138
							Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
							Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
							ETag: "3f80f-1b6-3e1cb03b"
							Accept-Ranges: bytes
							Connection: close
							
							<html>
							<head>
								An Example Page
							</head>
							<body>
								

Hello World, this is a very simple HTML document.

</body> </html>

HTTP Request & Response Example

HTTP Methods

  • indicate the desired action to be performed on the identified resource,
  • have their own semantics
    • safe: no side-effects
    • idempotent: can be replayed with no side-effects
  • are case-sensitive

HTTP Methods

method semantics Safe Idempotent
GET retrieve data YES YES
HEAD retrieve meta-information YES YES
POST create new resource NO NO
PUT replace resource NO YES
DELETE delete resource NO YES
OPTIONS retrieve supported methods YES YES
PATCH apply partial modifications NO NO

HTTP Status Codes

status code reason message
200 OK
301 Moved Permanently
304 Not Modified
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error

HTTP Characteristics

  • simple: readable and understandable by humans
  • extensible: by using custom headers
  • stateless: no link between two requests
  • not sessionless: cookies for stateful sessions
  • relient on TCP: as an reliable connection

HyperText Markup Language

standard markup language for documents designed to be displayed in a web browser

Basic HTML Page Structure (1 / 3)

						
							<!doctype html>
							<html dir="ltr" lang="en">
							<head>
								
								
								My first HTML Page
							</head>
							<body>
								

Hello world!

Lorem ipsum dolor sit amet

</body> </html>

Basic HTML Page Structure (2 / 3)

<!doctype html>
Document Type Definition (DTD). Tells browser to use HTML5 grammatics (render mode).
<html dir=”ltr” lang=”de”>
Root element. Can hold language metadata.
<head>
Contains metadata about the page...
<meta charset="utf-8">
… used charset,

Basic HTML Page Structure (3 / 3)

<meta name="viewport" content="width=device-width">
… render information for responsive behavior,
<title>My first HTML Page</title>
… document title.
<body>
Contains the visible part of the HTML document.

HTML Elements

  • are the building blocks of HTML documents,
  • consist of start tag and end tag with content between, e.g.

    Hello World

  • with no content are called empty elements, eg.

  • can be nested,
  • are case-insensitive and
  • can have attributes

HTML Attributes

  • Attributes provide additional information about an element
  • Attributes are always specified in the start tag
  • Attributes usually come in name/value pairs like name="value"
This is a link with href attribute

HTML Attributes

The global attributes below can be used on any HTML element.

Attribute Description
class Specifies one or more classnames for an element (refers to a class in a style sheet)
id Specifies a unique id for an element
style Specifies an inline CSS style for an element
tabindex Specifies the tabbing order of an element
title Specifies extra information about an element

Headings

See the Pen Headings by Johannes (@johakr) on CodePen.

Paragraphs, Line Breaks, Horizontal Rules, Preformatted Text

See the Pen Paragraphs by Johannes (@johakr) on CodePen.

Links

See the Pen Links by Johannes (@johakr) on CodePen.

Images

See the Pen Images by Johannes (@johakr) on CodePen.

Tables

See the Pen Tables by Johannes (@johakr) on CodePen.

Lists

See the Pen Lists by Johannes (@johakr) on CodePen.

Buttons

See the Pen Buttons by Johannes (@johakr) on CodePen.

Forms, Inputs, Labels

See the Pen Forms by Johannes (@johakr) on CodePen.

Containers

See the Pen Containers by Johannes (@johakr) on CodePen.

HTML 5 Semantic Elements

HTML5 introduced Semantic Elements, which clearly describe their content in a human and machine readable way.

HTML 5 Semantic Elements

HTML 5 Semantic Elements

2 main benefits

  • code is better readable by humans
  • content is more accessible to machines (screen readers & search engines)

Let’s start simple by building a mo’fuckin’ website about you

Cascading Style Sheets

Separation of content from its presentation

While HTML describes the content, CSS describes

  • how HTML elements are displayed (design & layout)
  • for different devices and screen sizes (responsive).

Same HTML different CSS

CSS Selector Syntax

CSS selectors are used to "find" (i.e. select) the HTML elements you want to style.

See the Pen Hello CSS by Johannes (@johakr) on CodePen.

CSS Selector Groups

Simple selectors select elements based on name, id, class
Combination selectors select elements based on a specific relationship between them
Pseudo-class selectors select elements based on a certain state
Pseudo-elements selectors select and style a part of an element
Attribute selectors select elements based on an attribute or attribute value

Simple Selectors (1 / 2)

class selector .intro Selects all elements with class="intro"
id selector #firstname Selects the element with id="firstname"
universal selector * Selects all elements
element selector p Selects all p elements
group selector div, p Selects all div and all p elements

Simple Selectors (2 / 2)

See the Pen Simple Selectors by Johannes (@johakr) on CodePen.

Pseudo-class Selectors (1 / 2)

p:first-child Selects every p element that is the first child of its parent
p:last-child Selects every p element that is the last child of its parent
p:nth-child(2n) Selects every p element that is the 2, 4, 6...th child of its parent
input:focus Selects inputs on focus
a:hover Selects links on mouse over
:not(p) Selects every element that is not a p element
button:disabled Selects every disabled button element

Pseudo-class Selectors (2 / 2)

See the Pen Pseudo-class Selectors by Johannes (@johakr) on CodePen.

Pseudo-elements selectors (1 / 2)

p::after Insert something after the content of each p element
p::before Insert something before the content of each p element
p::first-letter Selects the first letter of each p element
p::first-line Selects the first line of each p element
p::selection Selects the portion of an element that is selected by a user
CSS3 introduced the ::after notation (with two colons) to distinguish pseudo-classes from pseudo-elements. Browsers also accept :after, introduced in CSS2.

Pseudo-elements selectors (2 / 2)

See the Pen Pseudo-elements selectors by Johannes (@johakr) on CodePen.

Combination selectors (1 / 3)

descendant selector div p Selects all p elements inside div elements
child selector div > p Selects all p elements where the parent is a div element
adjacent sibling selector div + p Selects all p elements that are placed immediately after div elements
general sibling selector p ~ ul Selects every ul element that are preceded by a p element

Combination selectors (2 / 3)

See the Pen Combination Selectors by Johannes (@johakr) on CodePen.

Combination selectors (3 / 3)

The Lobotomized Owl Selector

See the Pen Lobotomized Owl by Johannes (@johakr) on CodePen.

Attribute selectors (1 / 2)

[alt] Selects all elements with a alt attribute
[target=_blank] Selects all elements with target="_blank"

Attribute selectors (2 / 2)

See the Pen Attribute selectors by Johannes (@johakr) on CodePen.

CSS Specificity (1 / 9)

If there are multiple conflicting CSS rules that point to the same element, the browser follows some rules to determine which one is most specific.

If there are 2 rules with the same specifity, the last one wins.

That’s why it’s called cascading style sheets.

The universal selector has no specificity

CSS Specificity (2 / 9)

https://css-tricks.com/specifics-on-css-specificity/

CSS Specificity (3 / 9)

https://css-tricks.com/specifics-on-css-specificity/

CSS Specificity (4 / 9)

https://css-tricks.com/specifics-on-css-specificity/

CSS Specificity (5 / 9)

https://css-tricks.com/specifics-on-css-specificity/

CSS Specificity (6 / 9)

https://css-tricks.com/specifics-on-css-specificity/

CSS Specificity (7 / 9)


::first-letter with two colons would be CSS3 compliant
https://css-tricks.com/specifics-on-css-specificity/

CSS Specificity (9 / 9)

								* { }
								li { }
								li::first-line
								ul li { }
								ul ol+li { }
								h1 + *[rel=up] { }	
								ul ol li.red { }
								li.red.level {}
								style=“”
								p { }
								div p { }
								div, p { }
								.sith { }
								div p.sith { }
								#sith { }
								body #darkside .sith p { }
								

CSS Specificity (9 / 9) Solution

                  * { } (0, 0, 0, 0)
                  li { } (0, 0, 0, 1)
                  li::first-line (0, 0, 0, 2)
                  ul li { } (0, 0, 0, 2)
                  ul ol+li { } (0, 0, 0, 3)
                  h1 + *[rel=up] { } (0, 0, 1, 1)
                  ul ol li.red { } (0, 0, 1, 3)
                  li.red.level {} (0, 0, 2, 1)
                  style=“” (1, 0, 0, 0)
                  p { } (0, 0, 0, 1)
                  div p { } (0, 0, 0, 2)
                  div, p { } (0, 0, 0, 1)
                  .sith { } (0, 0, 1, 0)
                  div p.sith { } (0, 0, 1, 2)
                  #sith { } (0, 1, 0, 0)
                  body #darkside .sith p { } (0, 1, 1, 2)
                  

CSS Specificity (8 / 9)

Specificity Calculator

CSS: Example Exercise


              ul#primary-nav li.active:not(:first-child) > a:hover::after {
                content: '⧉'
              }
            
  1. Describe in natural language what the css rule does.
  2. Provide a HTML structure with at least one element matched by the CSS selector.
  3. What's the CSS specificity of the given CSS selector in format (s,i,c,e)?
  4. You want to override the given CSS rule for a specific element which is selected by that rule. What options do you have?

How to include CSS

External CSS


							<head>
								<link rel="stylesheet" type="text/css" href="mystyle.css">
							</head>
						

Internal CSS


								<head>
										<style>
											body { background-color: linen; }
											</style>
								</head>
							

Inline CSS


							<body style="background-color: linen;"></body>
						

CSS Properties (1 / 2)

  • background, background-color, background-image
  • border, border-color, border-style, border-width, border-radius
  • color
  • cursor
  • display
  • font, font-family, font-size, font-width
  • height, width
  • letter-spacing, line-height
  • margin
  • overflow
  • padding
  • text-align, text-decoration
CSS Reference

CSS Properties (2 / 2)

See the Pen CSS Properties by Johannes (@johakr) on CodePen.

CSS Gotchas

QUIZ: Well aimed? How well do you know CSS selectors?

Let’s make things pretty by building a better mo’fuckin’ website about you

JavaScript

JavaScript Characteristics

  • high-level, interpreted scripting language
  • curly-bracket syntax (like C, Java...)
  • dynamic typing
  • prototype-based object orientation
  • first-class functions
  • multi-paradigm: event-driven, functional, object-oriented

History of JavaScript (Let there be JavaScript 1 / 2)

  • Early 1995 web designers needed a "glue" language to make their sites more dynamic
  • May 1995 Brendan Eich creates Mocha for Netscape in 10 days
  • Sep 1995 renamed to LiveScript for marketing reasons
  • Dec 1995 renamed to JavaScript for marketing reasons
https://dev.to/codediodeio/the-weird-history-of-javascript-2bnb

History of JavaScript (Let there be JavaScript 2 / 2)

  • Aug 1996 Microsoft reverse engineers JavaScript and ships it with IE 3, but calls it JScript
  • 1997 The first standardized version of JavaScript (ES1) is approved by the TC-39 committee as ECMAScript
  • 1999 ES3 is standardized. It will stand for the next 10 years.
https://dev.to/codediodeio/the-weird-history-of-javascript-2bnb

History of JavaScript (The Dark Ages)

  • 2000 The tech bubble bursts
  • 2005 Ajax gets popular
  • 2006 JQuery gets created and offers cross-browser compatibility
  • 2008 ES4 fails and gets abandoned
https://dev.to/codediodeio/the-weird-history-of-javascript-2bnb

History of JavaScript (The Renaissance)

  • 2008 Google releases the Chrome Browser and open-sources its high-performance runtime, called the V8 engine
  • 2009 NodeJS is created. It gives rise to the JavaScript Everywhere paradigm.
  • 2009 ES5 is standardized. (JSON support)
  • 2010 First Frameworks: Angular and Backbone
  • 2013 Facebook creates ReactJS
https://dev.to/codediodeio/the-weird-history-of-javascript-2bnb

History of JavaScript (Modern Times)

  • 2015 ES6 brings ton of new features. Transpilers like babel and typescript arise
  • 2016 ES7 arrives. (ECMA transforms to annual releases)
  • 2017 ES8 arrives. Async Await Syntax
  • 2017 Web Assembly (WASM) gets introduced
  • 2017 Browser Cryptomining (Coinhive)
  • 2018 ES9 arrives. Rest/Spread Syntax
https://dev.to/codediodeio/the-weird-history-of-javascript-2bnb

Values, Types, and Operators

See the Pen Values, Types, and Operators by Johannes (@johakr) on CodePen.

Program Structure

See the Pen Program Structure by Johannes (@johakr) on CodePen.

Functions

See the Pen Functions by Johannes (@johakr) on CodePen.

Data Structures: Objects and Arrays

See the Pen Data Structures by Johannes (@johakr) on CodePen.

Exercise: Fizz Buzz

Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead.

When you have that working, modify your program to print "FizzBuzz" for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those).

(This is actually an interview question that has been claimed to weed out a significant percentage of programmer candidates. So if you solved it, your labor market value just went up.)

Document Object Model

  • When a web page is loaded, the browser creates a DOM of the page.
  • The HTML DOM model is constructed as a tree of Objects.

Document Object Model

standard object model and programming interface for HTML

  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements


In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

Find HTML elements

using the power of CSS selectors

						
						// Find one (first) element matching css selector
						const element = document.querySelector('#id');

						// Find all elements matching css selector
						const elements = document.querySelectorAll('.className');
					

Change HTML elements

Mutate content, attributes & styles

						
							// Change the HTML content
							document.querySelector('p').innerHTML = 'new text';

						// Change any HTML attribute
							document.querySelector('img').src = '/kitty.png';
							document.querySelector('a').href = 'https://johakr.me';
							document.querySelector('input').value = 'Jane';

							// Change CSS styling 
							document.querySelector('p').style.color = 'red';
							document.querySelector('p').style.display = 'none';
						

DOM Events

DOM Events are things that

  • happen to HTML elements,
  • are triggered by either the browser or the user and
  • can be reacted to by JavaScript.

Examples

  • An HTML web page has finished loading
  • An HTML input field was changed
  • An HTML button was clicked

Adding Event Listeners

						
								const button = document.querySelector('button');	

								button.addEventListener('click', (evt) => {
									// evt.target = element which received the click event
									alert('YOU CLICKED THIS BUTTON', evt.target);
								});

								const form = document.querySelector('form');	

								form.addEventListener('submit', (evt) => {
									// prevent default submit action
									evt.preventDefault();

									// get all form values as JSON
									const values = Object.fromEntries(new FormData(e.target));
									console.log(values);
								});
							

Common Event Types

Ressource Events error, abort, load, unload
Focus Events focus, blur
Form Events submit, reset, change, input
View events resize, scroll
Keyboard events keydown, keypress, keyup
Mouse events click, mouseover, mouseout

Event reference

Exercise

Create a button, which displays the amount of received clicks.

Exercise: Solution

See the Pen dybdzEd by Johannes (@johakr) on CodePen.

JavaScript Object Notation (JSON)

  • a lightweight data-interchange format,
  • easy for humans to read and write,
  • easy for machines to parse and generate and
  • completely language independent.

JSON is built on three structures:

  • collection of name / value pairs (object, record, struct, dictionary, hash table, keyed list, associative array...)
  • ordered list of values (array, vector, list, sequence...)
  • primitives: string, number, boolean, null

JSON Example


                { 
                  "name": "John",
                  "age": 30,
                  "car": null,
                  "driverLicense": false,
                  "address": {
                    "city": "Stuttgart",
                    "street": "Theodor-Heuss-Straße"
                  },
                  "hobbies": ["reading", "cooking"]
                }
					
https://jsoneditoronline.org/?id=3e0486e4b8084baca52572bff563aefa

JSON Schema

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents.

https://json-schema.org/learn/miscellaneous-examples.html

JSON Schema Example


                  {
                    "$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "properties": {
                      "name": {
                        "type": "string",
                        "minLength": 2,
                        "maxLength": 32
                      },
                      "age": {
                        "type": "integer",
                        "minimum": 0,
                        "maximum": 150
                      },
                      "car": {
                        "type": [
                          "string",
                          "null"
                        ],
                        "enum": [
                          "mercedes",
                          "audi",
                          null
                        ]
                      },
                      "driverLicense": {
                        "type": "boolean"
                      },
                      "hobbies": {
                        "type": "array"
                      }
                    },
                    "required": [
                      "name",
                      "age",
                      "car",
                      "driverLicense",
                      "hobbies"
                    ]
                  }
            
https://www.jsonschemavalidator.net/

Promises

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Real Life Example

Hey Mr. Promise! Can you run to the store down the street and get me a bottle of tequilla?

Sure thing!

While you are doing that, I will cut the lemons.

Sounds good! See you in a bit.

There are 2 promises (asynchronous actions with indefinite outcome)

  • getting a bottle of tequilla
  • cutting the lemons

with 3 possible states respectively

  • pending: awaiting promise response
  • resolved: promise has successfully returned
  • rejected: failure occurred

            const cutLemons = () => new Promise((resolve, reject) => {
              const success = cutting(); // doing sth async

              if (success) {
                resolve("🍋🍋🍋")
              } else {
                reject("🤕🤕🤕");
              }
            });
      

        cutLemons() // pending
          .then(result => console.log(lemons)) // resolved 🍋🍋🍋
          .catch(error => console.log(error)) // rejected 🤕🤕🤕
      

In short, a Promise is an object that once called upon, will evetually resolve or reject and return a response based on some criteria that is specified within the Promise object.

Fetch API

The Fetch API provides an interface for fetching resources across the network...

...based on Promises.

Fetch: GET JSON Data


              fetch("https://swapi.co/api/people/") // request object
                .then(response => response.json()) // response object
                .then(json => console.log(json));
            

Fetch: POST JSON Data


                fetch("/login", { 
                  method: "POST",
                  body: JSON.stringify({ username: 'john', password: 'secure' }),
                  headers: {
                    "Content-Type": "application/json"
                  },
                 }) // request object
                  .then(response => response.json()) // response object
                  .then(json => console.log(json));
              

Fetch: Response Object

  • headers http response headers
  • ok boolean stating whether the response was successful (status in the range 200-299) or not.
  • status status code of the response (e.g., 200 for a success)
  • json() returns a promise that resolves with the result of parsing the body text as JSON
  • text() returns a promise that resolves with a string

Fetch: Request Object

  • headers http request headers
  • method http request method (GET, POST...)
  • body content for an api request which needs a body payload
  • credentials credentials of the request (e.g., "omit", "same-origin", "include"). The default is "same-origin"

Server Side Web Technology

A dynamic site can return different data for a URL based on information provided by the user or stored preferences and can perform other operations as part of returning a response

What can you do on the server-side?

  • Efficient storage and delivery of information
  • Customised user experience
  • Controlled access to content
  • Store session / state information
  • Notifications and communication
  • Data analysis
https://developer.mozilla.org/en-US/docs/Learn/Server-side/First_steps/Introduction

Web Architecture Overview

Your HTML gets dynamic, but who is in charge of creating the HTML markup?

  • Server: Server-side HTML
  • Both: JS Generation Widgets (Fetch)
  • Client: Single Page Applications (SPA)

Architecture I: Server-side HTML

HTML is completely composed on the server side

Architecture II: JS Generation Widgets

HTML Skeleton is composed on the server side & some data is exposed by a JSON API.
Parts of the DOM are created client-side by JavaScript

Architecture III: Single Page Applications

Server only provides data by JSON APIs.
DOM is completely composed on the client-side by JavaScript

Web Frameworks

will help you with

  • Work directly with HTTP requests and responses
  • Route requests to the appropriate handler
  • Make it easy to access data in the request
  • Abstract and simplify database access
  • Rendering data (working with JSON)

Web Frameworks

  • Python: Django, Flask
  • NodeJS: Express, Fastify
  • Ruby: Ruby on Rails
  • PHP: Laravel
  • Java: Spring Boot
  • Go: Gin

Server Side JavaScript: NodeJS

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

Node Package Manager (npm)

  • world's largest software registry
  • over 800,000 code packages
  • open-source developers use npm to share software
  • npm comes prebundled with node
A package is a reusable piece of software which can be downloaded from a global registry into a developer’s local environment. A package manager is a piece of software that lets you manage the dependencies (external code written by you or someone else) that your project needs to work correctly.

npm manifest file: package.json

Packages published to the registry must contain a package.json file.

  • lists the packages your project depends on
  • specifies versions of a package that your project can use using semantic versioning rules
  • makes your build reproducible, and therefore easier to share with other developers

npm manifest file: package.json


              {
                "name": "04-express",
                "version": "1.0.0",
                "description": "",
                "main": "index.js",
                "scripts": {
                  "start": "node index.js",
                  "test": "echo \"Error: no test specified\" && exit 1"
                },
                "author": "",
                "license": "ISC",
                "dependencies": {
                  "express": "^4.17.1"
                }
              }
            

NodeJS Quickstart


              npm init # creates project manifest (package.json)
              npm install express # installs the express web framework as a dependency
            

              // index.js
              const express = require('express');
              const app = express();
                
              app.get('/', (req, res) => {
                res.json({ hello: 'world' });
              });
                
              app.listen(3000);  
            

              node index.js # runs the server 
            

Building an API

An application programming interface (API) is an interface or communication protocol between a client and a server.

RESTful Web APIs

REpresentational State Transfer is an architectural style for distributed hypermedia systems (web apps).

  • Uniform interface: consistent naming conventions and data format for resources
  • Client–server: separating the user interface concerns from the data storage concerns
  • Stateless
  • Cacheable
  • Layered system

Resource Design

Use plural nouns, HTTP methods, status codes, JSON.

No trailing slashes, no file extensions.

  • GET /todos (collection)
  • GET /todos?userId=1 (filtered collection)
  • GET /todos/1 (resource)
  • POST /todos (create resource)
  • PUT /todos/1 (replace resource)
  • PATCH /todos/1 (update resource)
  • DELETE /todos/1 (delete resource)

REST Sequence Data Flow

Elliott, Eric. Programming JavaScript applications: Robust web architecture with node, HTML5, and modern JS libraries. " O'Reilly Media, Inc.", 2014.

ExpressJS

Fast, unopinionated, minimalist web framework for Node.js

  • Routing
  • HTTP Request / Response Handling with first class JSON support
  • Static File Handling
https://expressjs.com

ExpressJS: Routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST...).


              app.METHOD(PATH, HANDLER) 
            

              // GET /users
              app.get('/users', (req, res) => {
                // TODO: DO STUFF
              });
            

              // POST /users
              app.post('/', (req, res) => {
                // TODO: DO STUFF
              });
            

ExpressJS: HTTP Request

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.


              // GET /users/2
              app.get('/users/:id', (req, res) => {
                console.log(req.params.id) // access named route params
              })
            

              app.use(express.json()) // for parsing application/json

              // POST /users { username: 'john' }
              app.post('/users', (req, res) => {
                console.log(req.body.username) // access json request body 
              });
            

              // GET /users?age=26
              app.get('/users', (req, res) => {
                console.log(req.query.age) // access query string params 
              });
            

ExpressJS: HTTP Response

The res object represents the HTTP response that an Express app sends when it gets an HTTP request.


                app.get('/', (req, res) => {
                  return res.json({ }); // send json, status code 200 implicit
                });
              

                app.get('/', (req, res) => {
                  return res.status(204).send(); // send 204 response with empty body
                });
              

                app.get('/', (req, res) => {
                  return res.status(404).json({ error: 'not found' }); // send 404 with json body
                });
              

ExpressJS: Static File Handling

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.


                app.use(express.static('public')) // sends static files from the public directory
              

API Documentation

OpenAPI

OpenAPI Specification is an API description format for REST APIs. An OpenAPI file (JSON) allows you to describe your entire API, including:

  • Available endpoints (/users) and operations on each endpoint (GET /users, POST /users)
  • Operation parameters Input and output for each operation
  • Authentication methods
  • Contact information, license, terms of use...
Open API

OpenAPI Example


                {
                  "openapi": "3.0.0",
                  "info": {
                    "title": "Sample API",
                    "description": "Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.",
                    "version": "0.1.9"
                  },
                  "servers": [
                    {
                      "url": "http://api.example.com/v1",
                      "description": "Optional server description, e.g. Main (production) server"
                    },
                    {
                      "url": "http://staging-api.example.com",
                      "description": "Optional server description, e.g. Internal staging server for testing"
                    }
                  ],
                  "paths": {
                    "/users": {
                      "get": {
                        "summary": "Returns a list of users.",
                        "description": "Optional extended description in CommonMark or HTML.",
                        "responses": {
                          "200": {
                            "description": "A JSON array of user names",
                            "content": {
                              "application/json": {
                                "schema": {
                                  "type": "array",
                                  "items": {
                                    "type": "string"
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
					

Swagger

Excursion: JavaScript Fatigue

despite all of the language’s progress and growth, many developers have said they are dealing with JavaScript fatigue. JavaScript fatigue refers to the inability to keep up with the latest tools, the fear of becoming obsolete, the constant change of the ecosystem, and the overwhelming choice

How to Manage JavaScript Fatigue

Tutorial Hell

Every Programming Tutorial

Increasing Requirements

2019 is simultaneously a wonderful and also terrifying time for a newcomer to learn to code. There are so many resources out there! Awesome! But also, there are so many resources out there! Where does anyone even start?

Burnout is a thing

Imposter Syndrome

Developer Roadmap