Commit 79c91e44 authored by Nathan Bean's avatar Nathan Bean
Browse files

Added appendices and first chapters

parent 4bdcc112
......@@ -12,8 +12,9 @@ page = [ "HTML", "Iframeable", "Teleprompter"]
section = [ "HTML", "Iframeable", "Teleprompter"]
[params]
textbookURL = "https://cs.ksu.edu/~nhbean/cis526"
editURL = "https://gitlab.cs.ksu.edu/nhbean/cis526-textbook/tree/master/content/"
description = "K-State CS Hugo Framework"
description = "CIS 526 Textbook"
author = "Nathan H. Bean"
showVisitedLinks = false
themeVariant = "purple"
......
......@@ -22,8 +22,6 @@ This textbook was authored for the **CIS 526 - Web Application Development** cou
* [K-State Office of Student Life](https://www.k-state.edu/studentlife/)
* [K-State Report It](https://www.k-state.edu/report/)
#### Script
As you work on the materials in this course, you may run into questions or problems and need assistance. This video reviews the various types of help available to you in this course.
First and foremost, anytime you have a questions or need assistance in the course, please post in the course RocketChat room. It is the best place to go to get help with anything related to this course, from the tutorials and projects to issues with Codio and Canvas. Before you post on RocketChat, take a minute to look around and make sure the question has not already been posted before. It will save everyone quite a bit of time.
......
......@@ -9,6 +9,8 @@ date: 2018-08-24T10:53:26-05:00
This textbook was authored for the **CIS 526 - Web Application Development** course at Kansas State University. This front matter is specific to that course. If you are not enrolled in the course, please disregard this section.
{{% /notice %}}
The following is an outline of the topics we will be covering and when.
Week 1: Web Application Fundamentals
* Module: Exploring the Document Object Model<br>
* Readings 1.1-1.4
......
---
title: "Course Textbooks"
pre: "5."
weight: 50
date: 2018-08-24T10:53:26-05:00
---
{{% notice noiframe %}}
This textbook was authored for the **CIS 526 - Web Application Development** course at Kansas State University. This front matter is specific to that course. If you are not enrolled in the course, please disregard this section.
{{% /notice %}}
This course does not have a required print textbook. The resources presented in the modules are also organized into an online textbook that can be accessed here: [{{< param textbookURL >}}]({{< param textbookURL >}}). You may find this a useful reference if you prefer a traditional texbook layout. Additionally, since the textbook exists outside of Canvas' access control, you can continue to utilize it after the course ends.
{{% notice warning %}}
Please note that the materials presented in Canvas have additional graded assignments and exercises worked into the reading order that do not appear in the online edition of the textbook. You are responsible for completing these!
{{% /notice %}}
## O'Riley for Higher Education
If you are looking for additional resources to support your learning, a great resource that is availabe to Kansas State University students is the [O'Riley For Higher Education](https://go.oreilly.com/kansas-state-university) digital library offered through the Kansas State University Library. These include electronic editions of thousands of popular textbooks as well as videos and tutorials. As of this writing, a search for HTML returns 33,690 results, CSS 8,638 results, JavaScript 16,725 results, and Node.js 6,572 results.
There are likewise materials for other computer science topics you may have an interest in - it is a great resource for all your CS coursework. It costs you nothing (technically, your access was paid for by your tuition and fees), so you might as well make use of it!
---
title: "Syllabus"
pre: "5."
weight: 50
pre: "6."
weight: 60
date: 2018-08-24T10:53:26-05:00
---
......@@ -36,6 +36,16 @@ Fundamental principles and best practices of web development, user interface des
This course focuses on the creation of web applications - programs that use the core technologies of the world-wide-web to deliver interactive and dynamic user experiences. It builds upon a first course in authoring web pages using HTML/CSS/JavaScript, introduces the creation of web servers using the Node programming languages, and building sophisticated web clients using declarative component-based design frameworks like React.
### Course Objectives
The following are the learning objectives of this course:
1. Students will develop a thorough understanding of the http client request - server response pattern, and be able to implement multiple kinds of requests and responses, including HTML tags, browser-based JavaScript, programmatically, and with tools.
2. Students will understand and be able to make use of asynchronous programming, including creating original asynchronous functions and utilizing promises and the async/await key words.
3. Students will be able to develop traditional full-stack web applications using Node, a SQL database, and a Linux OS.
4. Students will be able to develop client-side [progressive] web applications using transpilation and minimization.
5. Students will be able to develop secure web applications using password authentication, cookies, and json web tokens.
### Major Course Topics
* The Document Object Model
* Responsive Web Design
......@@ -44,6 +54,7 @@ This course focuses on the creation of web applications - programs that use the
* Asynchronous functions
* Promises
* async/await
* HTTP
* AJAX & Fetch
* Routing
* REST
......@@ -60,7 +71,7 @@ This course is divided in modules, which typically consist of a series of lesson
For the eight-week summer course, each cluster of three modules plus project should be completed in one week. There is a lot to learn and much of the learning involved is hands-on as you work on the code for tutorials and your projects. It is recommended you set aside 10-20 hours per week to focus on this course.
Lessons are delivered in written or video (with written transcript) form. Sprinkled between lessons are quizzes that check your understanding of the readings and lecture content.
Lessons are delivered in written or video (with written transcript) form. Sprinkled between lessons are activities and quizzes that check your understanding of the readings and lecture content.
Tutorials are delivered through Codio, and offer immediate, automatically generated feedback as you complete the assignments, letting you know if you've made a mistake or skipped a step. You can run these assessments as many times as needed until you have completed the project to your satisfaction.
......@@ -68,11 +79,11 @@ The projects are more free-form - I want you to be able to flex your creative mu
### Grading
In this course, each assignment constitutes a a portion of the final grade, as detailed below:
* 30% - Tutorials
* 25% - Activities & Quizzes
* 35% - Tutorials
* 40% - Projects
* 20% - Quizzes
Up to 5% of the total grade in the course is available as extra credit. See the **Extra Credit - Bug Bounty** and **Extra Credit - Helpful Tutor** assignments for details.
Up to 5% of the total grade in the course is available as extra credit. See the **Extra Credit - Bug Bounty** and **Extra Credit - Helping Hand** assignments for details.
Letter grades will be assigned following the standard scale:
* 90% - 100% → A
......@@ -104,7 +115,9 @@ In particular you are encouraged to use:
* [CSS-Tricks](https://css-tricks.com/) - A collectiotn of guides and articles on using CSS to accomplish a variety of tasks
* [w3c.org](https://www.w3.org/) - The online home of the World-Wide-Web Consortium, the organization that sets web technology standards
Since this class covers such a wide swath of web technologies, no single textbook will suffice. Therefore, students who would like a textbook should refer to resources available on the [O'Riley For Higher Education](https://go.oreilly.com/kansas-state-university) digital library offerd by the Kansas State University Library. These include electronic editions of popular textbooks as well as videos and tutorials.
This course offers an instructor-written textbook, which is broken up into a specific reading order and interleaved with activities and quizzes in the modules. It can also be directly accessed at [{{< param textbookURL >}}]({{< param textbookURL >}}).
Students who would like additional textbooks should refer to resources available on the [O'Riley For Higher Education](https://go.oreilly.com/kansas-state-university) digital library offerd by the Kansas State University Library. These include electronic editions of popular textbooks as well as videos and tutorials.
### Subject to Change
......@@ -116,7 +129,16 @@ Kansas State University has an Honor and Integrity System based on personal inte
**For this course, a violation of the Honor Pledge will result in an automatic 0 for the assignment and the violation will be reported to the Honor System. A second violation will result in an XF in the course.**
The Codio platform can perform automatic plagiarism detection by comparing submitted projects against other students’ submissions and known solutions. That information may be used to determine if plagiarism has taken place.
In this course, _unauthorized aid_ broadly consists of _giving or reciving code to complete assignments_. This could be code you share with a classmate, code you have asked a third party to write for you, or code you have found online or elsewhere.
Authorized aid - which is not a violation of the honor policy - includes
using the code snippets provided in the course materials, discussing strategies and techniques with classmates, instructors, TAs, and mentors. Additionally, you may use code snippets and algorithms found in textbooks and web sources if you clearly label them with comments indicating where the code came from and how it is being used in your project.
You should restrict your use of code libraries to those specified in the assignment description or approved by the instructor. You can ask for approval via RocketChat in the course channel, and if granted, this approval is valid for the entire class _for the specified assignment_.
{{% notice info %}}
While code libraries are an important and common tool in professional practice, at this point in your learning they can obscure how tasks are being accomplished, leaving your foundational knowledge incomplete. It is for this reason that we restrict the use of code libraries in the course.
{{% /notice %}}
### Students with Disabilities
......@@ -172,6 +194,6 @@ Kansas State University is a community of students, faculty, and staff who work
Moreover, academic freedom supports collaborative work in the pursuit of truth and the dissemination of knowledge in an environment of inquiry, respectful debate, and professionalism. Academic freedom is not limited to the classroom or to scientific and scholarly research, but extends to the life of the university as well as to larger social and political questions. It is the right and responsibility of the university community to engage with such issues.
### Copyright Notice
© The materials in this online course fall under the protection of all intellectual property, copyright and trademark laws of the U.S. The digital materials included here come with the legal permissions and releases of the copyright holders. These course materials should be used for educational purposes only; the contents should not be distributed electronically or otherwise beyond the confines of this online course. The URLs listed here do not suggest endorsement of either the site owners or the contents found at the sites. Likewise, mentioned brands (products and services) do not suggest endorsement. Students own copyright to what they create.
©2020 The materials in this online course fall under the protection of all intellectual property, copyright and trademark laws of the U.S. The digital materials included here come with the legal permissions and releases of the copyright holders. These course materials should be used for educational purposes only; the contents should not be distributed electronically or otherwise beyond the confines of this online course. The URLs listed here do not suggest endorsement of either the site owners or the contents found at the sites. Likewise, mentioned brands (products and services) do not suggest endorsement. Students own copyright to what they create.
Original content licensed under a Creative Commons BY-SA license by Nathan Bean unless otherwise stated.
\ No newline at end of file
Original content in the course textbook at [{{< param textbookURL >}}]({{< param textbookURL >}}) is licensed under a Creative Commons BY-SA license by Nathan Bean unless otherwise stated.
\ No newline at end of file
......@@ -10,6 +10,6 @@ At this point, you should be familiar with the big three technologies of the wor
* Cascading Style Sheets (CSS) determine how that content should appear visually
* JavaScript provides interactivity, allowing both the structure and appearance of the page to change dynamically
We often refer to this division of responsiblity as the _separation of concerns_. By placing all responsibility for appearance on a CSS file, we can refresh the look of a web application simply by replacing the old CSS file with a new one. Similarly, we can create a new page in our site that looks and feels like the rest of the site by creating a new HTML page that links to the site's existing CSS files.
We often refer to this division of responsiblity as the [separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns). By placing all responsibility for appearance on a CSS file, we can refresh the look of a web application simply by replacing the old CSS file with a new one. Similarly, we can create a new page in our site that looks and feels like the rest of the site by creating a new HTML page that links to the site's existing CSS files.
While you have written HTML, CSS, and JavaScript files in your prior learning experiences, you might not have thought about just how these files are processed, and those styling rules applied. In this chapter we will explore this topic in detail, while introducing some more advanced uses for each.
\ No newline at end of file
......@@ -48,7 +48,7 @@ Similarly, the `.banner p` tag uses the [descendant combinator](https://develope
![DOM tree visualization with marked .banner p nodes]({{<static "images/1.3.4.png">}})
You can see the example with the styling applied by following <a href='{{<static "images/1.3.2.png">}}' target='_blank'>this link</a>. Try adding the div and two paragraphs with the developer tools. See how the styles are automatically applied to the new nodes in the DOM tree?
You can see the example with the styling applied by following <a href='{{<static "examples/1.3.1/index.html">}}' target='_blank'>this link</a>. Try adding the div and two paragraphs with the developer tools. See how the styles are automatically applied to the new nodes in the DOM tree?
### CSS and Developer Tools
......
---
title: "JavaScript and the DOM"
pre: "5. "
weight: 50
pre: "4. "
weight: 40
date: 2018-08-24T10:53:26-05:00
---
......@@ -121,4 +121,18 @@ As soon as it is appended, it appears on the page:
![The new p element]({{<static "images/1.4.6.png">}})
Note too that the CSS rules already in place are automatically applied!
\ No newline at end of file
Note too that the CSS rules already in place are automatically applied!
{{% notice info %}}
The popular [JQuery](https://jquery.com/) library was created primarily as a tool to make DOM querying and manipulation easier at a time when browsers were not all adopting the w3c standards consistently. It provided a simple interface that worked identically in all commonly used browsers.
The JQuery function (commonly aliased to `$()`) operates much like the `querySelectorAll()`, taking a CSS selector as an argument and returning a collection of matching elements wrapped in a JQuery helper object. The helper object provided methods to access and alter the attributes, style, events, and content of the element, each returning the updated object allowing for functions to be 'chained' into a single expression.
The above example, rewritten in JQuery, might be:
```js
$('p').text('Tra-la-la').appendTo('div.banner');
```
While modern browsers are much more consistent at supporting standardized JavaScript, JQuery remains a popular library and one you will likely encounter. Thus, while this text focuses on 'vanilla' JavaScript, we'll also occasonally call out JQuery approaches in blocks like this one.
{{% /notice %}}
\ No newline at end of file
---
title: "JavaScript Events"
pre: "5. "
weight: 50
date: 2018-08-24T10:53:26-05:00
---
It should be no surpise that JavaScript features events - after all, we've already seen how the [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) interface allows us to attach event listeners to elements in the DOM tree. What might not be clear yet is how events are handled by JavaScript. JavaScript uses an _event loop_ to process events. This is similar to Windows and other operating systems also handle events.
An event loop expressed in code looks something like:
```
function main
initialize()
while message != quit
message := get_next_message()
process_message(message)
end while
end function
```
It's basically an infinite loop that responds to messages, one message at a time. It might be more useful to see a visual respresentation:
![The JS Event Loop]({{<static "images/1.6.1.png">}})
Here we see not just the event loop, but also the _event queue_. This is a queue that holds events until the event loop is ready to process them. It works like the first-in-first-out queues you built in your data structures course (although it may also consider priorities of events).
On the far right are some commoon sources for JavaScript events - user input, the network, and timers. These are often managed by the operating system, and with modern multiple-processor computers can happen _concurrently_, i.e. _at the same time_. This is one reason the queue is so important - it allows JavaScript to process the events _one at a time_.
When the JavaScript VM has finished executing its current work, it pulls the next event from the event queue. This event is processed by the corresponding _event listener_ function that either 1) you wrote, or 2) is the default action. If neither exists, the event is discarded.
### An Example
Consider when the user clicks on a link on your page, let's say `<a id="demo" href="https://google.com">Google it!</a>`. This creates a 'click' event for the `<a>` tag clicked on. Now let's assume you've written an event handler and attached it to that anchor tag:
```js
document.getElementById('demo').addEventListener('click', function(e) {
e.preventDefault();
alert('You clicked the "Google it!" link.');
});
```
The anonymous function `function(e) {...}` attached to the `<a>`'s 'click' event is invoked, with the event details being passed as the parameter `e`. Anchor tags have a default behavior - they open the linked page. So the line `e.preventDefault();` informs JavaScript _not_ to use this default behavior. Then we trigger an alert with the string `'You clicked the "Google it!" link.'`.
If we hadn't attached the event listener, then the page would have used the default response - loading a new page into the browser in the place of our current page.
If we clicked on an element that didn't have a default action (like a `<p>` element) and you haven't attached a listener the event is discarded and does nothing.
### Concurrency in JavaScript
An important takeaway from the discussion of the event loop is that the actual processing of JavaScript code is always _single-threaded_. This avoids many of the common challenges of multi-threaded code. You don't need to create semaphores, locks, and other multi-threading synchronization tools as your code will always be executing in a single thread.
However, JavaScript _does_ retain many of the benefits of concurrency within its model. For example, when the DOM is loading and encounters an element referencing an external resource (i.e. a `video`, `img`, `link`, or `script` element), it triggers a request to retrieve that resource through the browser. The browser does so _while the JavaScript code continues executing_. When the resource is fully downloaded by the browser, it creates a `'load'` event with the details, and adds it to the JavaScript event queue. Multiple files are therefore downloaded _concurrently_, but our JavaScript handles the results one-by-one in a single-threaded manner.
Think of the JavaScript event loop as a busy manager that only works on one thing at a time. He might send several workers out to get information. When they return, they form a line in front of his desk and wait patiently. Once he finishes the task he has been working on, he takes the report from the first worker in line, and starts doing what he needs to do with the returned information. Once he finishes that, he has the second employee report, and so on.
## Common Events
There are many kinds of events in JavaScript; you can find a complete list in the [mdn docs](https://developer.mozilla.org/en-US/docs/Web/Events). However some of the ones you will likely find yourself using are:
* [load](https://developer.mozilla.org/en-US/docs/Web/Events/load) - Triggered when a resource (i.e. an image, video, stylesheet, script) has finished loading. You can also listen for the load event on the `document` itself; here it will be triggered after _all_ the resources on the page are loaded.
* [change](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) The value of an `<input>`, `<textarea>`, or `<select>` has changed
* [focus](https://developer.mozilla.org/en-US/docs/Web/Events/focus) triggered when an input gains focus (is the currently selected input)
* [blur](https://developer.mozilla.org/en-US/docs/Web/Events/blur) triggered when an input looses focus
* [click](https://developer.mozilla.org/en-US/docs/Web/Events/click) The primary mouse button was clicked. On old browsers this might trigger for any button
* [contextmenu](https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu) The right mouse button was clicked
* [mousedown](https://developer.mozilla.org/en-US/docs/Web/Events/mousedown) A mouse button was pressed
* [mouseup](https://developer.mozilla.org/en-US/docs/Web/Events/mouseup) A mosue button was released
## Timers
Timers play a special role in JavaScript's concurrency model, and in many ways behave like events. For example, to cause the phrase "Hello time!" to be logged to the console in three minutes, you would write the code:
```js
setTimeout(function() { console.log("Hello time!")}, 3000);
```
You will notice that the [setTimeout()](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) method takes a function to execute at that future point in time, much like attaching an event handler. The second argument is the number of milliseconds in the future for this event to occur. The timer works like an event, when the time expires, a corresponding event is added to the event queue, to trigger the delayed function.
An important side-effect of this approach is that you only know the timer's result won't happen _before_ the delay you specify, but if the JavaScript vm is engaged in a long-running process, it may be longer before your timer event is triggered.
For events you need to do on a regular interval, use [setInterval()](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) instead. This will invoke the supplied function at each elapsing of the supplied interval. It also returns a unique id that can be supplied to [clearInterval()](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval) to stop the timed event.
{{% notice info %}}
You may find yourself reading code that uses a value of `0` milliseconds with `setTimeout()`, i.e.:
```js
setTimeout(doSomething, 0);
```
You might be wondering why. You might wonder if it is equivalent to:
```js
doSomething();
```
And while it might appear that way, the answer is _no_. Remember, `setTimeout()` creates an event in the event queue that executes after the specificed delay. Thus, `doSomething()` will execute _immediately_, but `setTimout(doSomething())` will continue to execute all code _after_ the line until execution finishes, and _then_ will invoke `doSomething()`.
Thus, JavaScript programmers often use this technique to trigger an action immedately after the current code finishes executing.
{{% /notice %}}
\ No newline at end of file
---
title: "The DOM and External Resource Loading"
pre: "6. "
weight: 60
date: 2018-08-24T10:53:26-05:00
---
One of the important aspects of working with HTML is understanding that an HTML page is _more_ than just the HTML. It also invovles a collection of resources that are external to the HTML document, but displayed or utilized by the document. These include elements like `<link>`, `<script>`, `<video>`, `<img>`, and `<source>` with `src` or `href` attributes set.
As the DOM tree is parsed and loaded and these external resources are encountered, the browser requests those resources as well. Modern browsers typically make these requests in parallel for faster loading times.
Once the HTML document has been completely parsed, the `window` triggers the [DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event) event. This means the HTML document has been completely parsed and added to the DOM tree. However, the external resources _may not have all been loaded at this point_.
Once those resources are loaded, a separate [Load](https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event) event is triggered, also on the `window`.
Thus, if you have JavaScript that should only be invoked _after_ the page has fully loaded, you can place it inside an event listener tied to the `load` event, i.e.:
```javascript
window.addEventListener('load', function(event) {
// TODO: Add your code here ...
});
```
Or, if you want it invoked after the DOM is fully parsed, but external resources may still be loading:
```javascript
window.addEventListener('DOMContentLoaded', function(event) {
// TODO: Add your code here ...
});
```
The former - waiting for all resources to load - tends to be the most common. The reason is simple, if you are loading multiple JavaScript files, i.e. a couple of libraries and your own custom code, using the `'load'` event ensures they have all loaded before you start executing your logic.
Consider the popular [JQuery](https://jquery.com/) library, which provides shorthand methods for querying and modifying the DOM. It provides a `JQuery()` function that is also aliased to the `$`. The JQuery code to show a popup element might be:
```javascript
$('#popup').show();
```
But if the JQuery library isn't loaded yet, the `$` is not defined, and this logic will crash the JavaScript interpreter. Any remaining JavaScript will be ignored, and your page won't work as expected. But re-writing that to trigger after all resources have loaded, i.e.:
```javascript
window.addEventListener = function(event) {
// This code only is executed once all resources have been loaded
$('#popup').show();
}
```
Ensures the JQuery library is available before your code is run.
{{% notice info %}}
JavaScript is an extremely flexible langauge that has evolved over time. One side effect of this evolution is that there are often multiple ways to express the same idea. For example, listening for the `window`'s `'load'` event can be written many different ways:
```javascript
// Using the onload property
window.onload = function(event) {...}
// Using onload property and lambda syntax
window.onload = (event) => {...}
// Using the addEventListener and lambda syntax
window.addEventListener('load', (event) => {
...
});
// Using the JQuery library
JQuery(function(){...});
// Using the JQuery library with lambda syntax
JQuery(() => {...});
// Using the JQuery library with $ alias
$(function(){...});
```
You are free to use whichever approach you like, but need to be able to interpret other programmers' code when they use a different approach.
{{% /notice %}}
## Loading Resources _after_ the DOM is loaded
There are really _two_ ways to load resources into an HTML page from your JavaScript code. One is indirect, and the other direct. The indirect method simply involves creating DOM elements linked to an outside resource, i.e.:
```js
var image = document.createElement('img');
image.src = 'smile.png';
document.body.appendChild(img);
```
In this case, when the new `<img>` element has its `src` attribute set, the image is requested by the browser. Attaching it to the DOM will result in the image being displayed once it loads.
If we want to know when the image is loaded, we can use the `load` event:
```js
var image = document.createElement('img');
image.addEventListener('load', function(event){
console.log('loaded image');
});
image.src = 'smile.png';
```
Notice too that we add the event listener _before_ we set the `src` attribute. If we did it the other way around, the resource may already be loaded before the listener takes effect - and it would never be invoked!
However, this approach can be cumbersome, and limits us to what resources can be bound to HTML elements. For more flexiblity, we need to make the request directly, using AJAX. We'll take a look at doing so after we cover HTTP in more depth.
\ No newline at end of file
+++
title = "Web Application Foundations"
title = "The DOM"
date = 2018-08-24T10:53:05-05:00
weight = 10
chapter = true
......@@ -8,6 +8,6 @@ pre = "<b>1. </b>"
### Chapter 1
# Web Application Foundations
# The Document Object Model
Digging Deeper into Core Web Technologies
HTML, CSS, and JavaScript in the Browser
---
title: "The DOM and Page Loading"
pre: "7. "
weight: 70
date: 2018-08-24T10:53:26-05:00
---
\ No newline at end of file
---
title: "Introduction"
pre: "1. "
weight: 10
date: 2018-08-24T10:53:26-05:00
---
At the heart of the world wide web is the Hyper-Text Transfer Protocol (HTTP). This is a protocol defining how HTTP servers (which host web pages) interact with HTTP clients (which display web pages).
It starts with a request initiated from the web browser (the client). This request is sent over the Internet using the TCP protocol to a web server. Once the web server receives the request, it must decide the appropriate response - ideally sending the requested resource back to the browser to be displayed. The following diagram displays this typical request-response pattern.
![HTTP's request-response pattern]({{<static "images/2.0.1.png">}})
This HTTP request-response pattern is at the core of how all web applications communicate. Even those that use websockets begin with an HTTP request.
{{% notice info %}}
The HTTP standard, along with many other web technologies, is maintained by the [World-Wide-Web Consortium](https://www.w3.org/) (abbrivated W3C), stakeholders who create and maintain web standards. The full description of the Hyper-Text Transfer Protocol can be found here [w3c's protocols page](https://www.w3.org/Protocols/).
{{% /notice %}}
---
title: "Browser Requests"
pre: "2. "
weight: 20
date: 2018-08-24T10:53:26-05:00
---
Before we get too deep in the details of what a request is, and how it works, let's explore the primary kind of request you're already used to making - requests originating from a browser. Every time you use a browser to browse the Internet, you are creating a series of HTTP (or HTTPS) requests that travel across the networks between you and a web server, which responds to your requests.
To help illustrate how these requests are made, we'll once again turn to our developer tools. Open the example page <a href='{{<static "examples/1.3.1/index.html">}}' target='_blank'>this link</a>. On that tab, open your developer tools with `CTRL + SHIFT + i` or by right-clicking the page and selecting "Inspect" from the context menu. Then choose the "Network" tab:
![Selecting the network tab in the developer tools]({{<static "images/2.2.1.png">}})
The network tab displays details about each request teh browser makes. Initially it will probably be empty, as it does not log requests while not open. Try refreshing the page - you should see it populate with information:
![The populated network tab]({{<static "images/2.2.2.png">}})
The first entry is the page itself - the HTML file. But then you should see entries for _site.css_, _brazil.gif_, *fiber-4814456_960_720.jpg*, _jquery-3.5.1.slim.min.js_, and _site.js_. Each of these entries represents an additional resource the browser fetched from the web in order to display the page.
Take, for example, the two images _brazil.gif_ and *fiber-4814456_960_720.jpg*. These correspond to `<img>` tags in the HTML file:
```html
<img alt="Paper scene from the film Brazil" src="brazil.gif"/>
<img alt="Fiber optic cables" src="https://cdn.pixabay.com/photo/2020/02/03/00/12/fiber-4814456_960_720.jpg"/>
```
The important takeaway here is that the image is requested _separately_ from the HTML file. As the browser reads the page and encounters the `<img>` tag, it makes an additional request for the resource supplied in its `src` attribute. When that second request finishes, the downloaded image is added to the web page.
Notice too that while one image was on our webserver, the other is retrieved from [Pixabay.com](https://pixabay.com)'s server.
Similarly, we have two JavaScript files:
```html
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
<script src="site.js"></script>
```
As with the images, one is hosted on our website, _site.css_, and one is hosted on another server, [jquery.com](https://code.jquery.com/jquery-3.5.1.slim.min.js).
Both the Pixabay image and the jQuery library are hosted by a [Content Delivery Network](https://en.wikipedia.org/wiki/Content_delivery_network)- a network of proxy servers that are distributed geographically in such a way that a request for a resource they hold can be processed from a nearby server. Remember that the theoretical maximum speed for internet transmissions is the speed of light (for fiber optics) or electrons in copper wiring. Communication is further slowed at each network switch encountered. Serving files from a nearby server can prove very efficient at speeding up page loads because of the shorter distance and smaller number of switches involved.
A second benefit of using a CDN to request the JQuery library is that if the browser has previously downloaded the library when visting another site it will have cached it. Using the cached version instead of making a new request is _much_ faster. Your app will benefit by faster page loads that use less bandwidth.
Notice too that the jQuery `<script>` element also uses the `integrity` attribute to allow the browser to determine if the library downloaded was tampered with by comparing cryptographic tokens. This is an application of [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity), a feature that helps protect your users. As JavaScript can transform the DOM, there are incentives for malicious agents to supplant real libraries with fakes that abuse this power. As a web developer you should be aware of this, and use all the tools at your disposal to keep your users safe.
You can use the network tab to help debug issues with resources. Click on one of the requested resources, and it will open up details about the request:
![Request details in the Network Tab]({{<static "images/2.2.3.png">}})
Notice that it reports the status code along with details about the request and response, and provides a preview of the requested resource. We'll cover what these all are over the remainder of this chapter. As you learn about each topic, you may want to revisit the tab with the example to see how these details correspond to what you are learning.
\ No newline at end of file
---
title: "Request Format"
pre: "3. "
weight: 30
date: 2018-08-24T10:53:26-05:00
---
So now that we've seen HTTP Requests in action, let's examine what they _are_. A HTTP Request is just a stream text that follows a specific format and sent from a client to a server.
![Http Request as a stream of text]({{<static "images/2.3.1.png">}})
It consists of one or more lines terminated by a CRLF (a carriage return and a line feed character, typically written `\r\n` in most programming languages).
1. A _request-line_ describing the request
2. Additional optional lines containing HTTP headers. These specify details of the request or describe the body of the request
3. A blank line, which indicates the end of the request headers
4. An optional body, containing any data belonging of the request, like a file upload or form submission. The exact nature of the body is described by the headers.
## The Request-Line
The request-line follows the format
`Request-Line = Method SP Request-URI SP HTTP-Version CRLF`
The _Method_ refers to the HTTP Request Method (often GET or POST).
_SP_ refers to the space character.
The _Request-URI_ is a Universal Request Indicator, and is typically a URL or can be the asterisk character (\*), which refers to the server instead of a specific resource.
_HTTP-Verson_ refers to the version of the HTTP protocol that will be used for the request. Currently three versions of the protocol exist: `HTTP/1.0`, `HTTP/1.1`, and `HTTP/2.0`. Most websites currently use HTTP/1.1 (HTTP/2.0 introduces many changes to make HTTP more efficient, at the cost of human readability. Currently it is primarily used by high-traffic websites).
Finally, the _CRLF_ indicates a carriage return followed by a line feed.
For example, if we were requesting the about.html page of a server, the request-line string would be:
`GET /about.html HTTP/1.1\r\n`
## The Headers
Header lines consist of key-value pairs, typically in the form
`Header = Key: Value CRLF`
Headers provide details about the request, for example, if we wanted to specify we can handle the _about.html_ page data compressed with the gzip algorithm, we would add the header:
`Accept-Encoding: compress, gzip\r\n`
The server would then know it could send us a zipped version of the file, resulting in less data being sent from the server to the client.
If our request includes a body (often form data or a file upload), we need to specify what that upload data is with a Content-Type header and its size with a Content-Length header, i.e.:
`Content-Length: 26012
Content-Type: image/gif`
## A Blank Line
The header section is followed by a blank line (a CRLF with no characters before it). This helps separate the request metadata from the request body.
## The Request Body
The body of the request can be text (as is the case for most forms) or binary data (as in an image upload). This is why the Content-Type header is so important for requests with a body; it lets the server know how to process the data. Similarly, the Content-Length header lets us know how many bytes to expect the body to consist of.
It is also acceptable to have no body - this is commonly the case with a GET request. If there is no body, then there are also no required headers. A simple get request can therefore consist of only the request-line and blank line, i.e.:
`GET /about.html HTTP/1.1\r\n\r\n`
{{% notice info %}}
The HTTP/1.1 request definition can be found in [W3C RFC 2616 Section 5](https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5)
{{% /notice %}}
---
title: "Request Methods"
pre: "4. "
weight: 40
date: 2018-08-24T10:53:26-05:00
---
The first line of the HTTP request includes the __request method__, which indicates what kind of action the request is making of the web server (these methods are also known as __HTTP Verbs__). The two most common are _GET_ and _POST_, as these are supported by most browsers.
### Commonly HTTP Methods
The following requests are those most commonly used in web development. As noted before GET and POST requests are the most commonly used by web browsers, while GET, PUT, PATCH, and DELETE are used by RESTful APIs. Finally, HEAD can be used to optimize web communications by minimizing unnecessary data transfers.
#### GET
A _GET_ request seeks to retrieve a specific resource from the web server - often an HTML document or binary file. GET requests typically have no body and are simply used to retrieve data. If the request is successful, the response will typically provide the requested resource in its body.
#### HEAD
A _HEAD_ request is similar to a GET request, except the response is not expected to provide a body. This can be used to verify the type of content of the resource, the size of the resource, or other metadata provided in by the response header, without downloading the full data of the resource.
#### POST
The _POST_ request submits an entity to the resource, i.e. uploading a file or form data. It typically will have a body, which is the upload or form.
#### PUT
The _PUT_ request is similar to a POST request, in that it submits an entity as its body. It has a more strict semantic meaning though; a PUT request is intended to _replace_ the specified resource in its entirety.
#### PATCH