1 of 22

Client-Side Templating & Fetch

CS 396: �Introduction to Web Development

Spring, 2022

2 of 22

Outline

  1. Review
  2. Intro to AJAX & Fetch
  3. Error handling
  4. Headers & CORs
  5. Practice

3 of 22

Outline

  • Review
  • Intro to AJAX & Fetch
  • Error handling
  • Headers & CORs
  • Practice

4 of 22

Recall: Server-Side Templates

In HW2, the Photo App interface was generated on the server. Specifically:

  1. Python fetched the data from “faker” (but could have been from a database too)
  2. Python “merged” this data with a template (using Jinja) to create a fully-generated HTML file
  3. Python then sent this HTML file down to the client:
    1. Demo: https://photo-app-demo.herokuapp.com/

5 of 22

Next Two Weeks: Client-Side Templating

In HW4, we will practice building client-side templates. Specifically:

  • Server sends down the skeleton of an HTML page with some embedded JavaScript
  • Then, the Browser reads the instructions from the JavaScript files and dynamically builds the page on-the-fly by manipulating the DOM
  • Typically, either:
    • JSON is embedded in the page as a variable, or
    • Data is fetched after the pages loads via a REST API endpoint.

�Example: https://www.instagram.com/

6 of 22

Outline

  • Review
  • Intro to AJAX & Fetch
  • Error handling
  • Headers & CORs
  • Practice

7 of 22

1. Intro to AJAX

AJAX

  • AJAX: Stands for Asynchronous JavaScript and XML
  • Enables JavaScript to make server requests and (optionally) update the current screen
  • Not easy to tell that information is even being transmitted to/from a server
  • Came on the scene ~2004 (made popular w/Google Mail and Google Maps)

7

8 of 22

1. Intro to Fetch

JavaScript’s Fetch API

  • The Fetch API is a newer instantiation of asynchronous server-client web communication
  • Provides an interface for fetching resources (including across the network). The new API provides a more powerful and flexible feature set (improving upon AJAX)

8

9 of 22

1. How Fetching a Web Resource Works

fetch(url)

.then(response => {

// handle the response

})

.catch(err => {

// handle the error

});

  • The fetch asks for an HTTP response object. It returns a promise.
  • If the promise resolves, the function inside the “then” method is invoked. The function’s argument is the result of the promise.
  • If the promise is rejected, then the function inside the “catch” method is invoked.

10 of 22

1. Most Network Requests Happen in 2 Parts (w/2 Promises)

fetch('https://some-url.com')

.then(response => response.json()) // callback function

.then(data => console.log(data)); // callback function

  • fetch() returns a promise containing the response (a Response object). This is just an HTTP response, not the actual content.
  • To extract the body content from the response, we use one of the response’s content methods – in this case the json() method – which also returns a promise with the actual data.

11 of 22

2. What is a Promise?

  • Promises exist to handle asynchronous functionality
  • If you request a resource the cloud (i.e., someone else’s computer that lives somewhere else), you don’t know how long it’s going to take to process the request.
    • Slow machine?
    • Network traffic?
    • Patchy WIFI!
  • To handle this, a “promise” allows you to execute a piece of functionality only after the request completes.

12 of 22

2. Promises: Two Syntaxes > “then” method

Using the promise’s “then” method, which will execute a callback function when the promise finishes its business...�

let url = 'https://www.apitutor.org/yelp/simple/v3/businesses/search?location=Asheville,+NC'

fetch(url)

.then(response => response.json()) // callback function

.then(data => console.log(data)); // callback function

13 of 22

2. Promises: Two Syntaxes > async await

Using the async / await technique. Instead of using “then()” the await keyword ensures that the next line doesn’t execute until the promise resolves.

const getPosts = async () => {

let url = 'https://www.apitutor.org/yelp/simple/v3/businesses/search?location=Asheville,+NC';

const response = await fetch(url);

console.log(response);

const jsonData = await response.json();

console.log(jsonData);

};

getPosts();

14 of 22

Outline

  • Review
  • Intro to AJAX & Fetch
  • Error handling
  • Headers & CORs
  • Practice

15 of 22

Error Handling

  • If the response has an error code (e.g. HTTP 404, 400, or 500), the except won’t get triggered.
  • It will resolve normally, but the ok property of the response set to false if the response isn’t in the range 200–299)
  • It will only reject on network failure or if anything prevented the request from completing.

16 of 22

Example: No Error Handling

fetch(''https://www.apitutor.org/yelp/simple/v3/businesses/search?location=Asheville,+NC'')

.then(response => response.json())

.then(data => {

console.log('Success:', data);

});

17 of 22

Example: With Error Handling

fetch('https://www.apitutor.org/yelp/simple/v3/businesses/search?location=Asheville,+NC')

.then(response => {

if (!response.ok) {

// send to catch block:

throw Error(response.statusText);

} else {

return response.json();

}

})

.then(data => {

console.log('Success:', data);

})

.catch(err => {

console.error('Error:', err);

});

18 of 22

Example: With Error Handling

const getBusinesses = async () => {

try {

let url = 'https://www.apitutor.org/yelp/simple/v3/businesses/search?location=Asheville,+NC';

const response = await fetch(url);

console.log(response);

const jsonData = await response.json();

console.log(jsonData);

} catch(err) {

console.error(err);

}

};

getPosts();

19 of 22

Outline

  • Review
  • Intro to AJAX & Fetch
  • Error handling
  • Headers & CORs
  • Practice

20 of 22

Cross-Origin Resource Sharing (CORS)

  • Some kinds of requests have an extra security check called a “preflighted request” (see this MDN article). In these requests, the browser and server communicate to determine whether the request is safe to send based on particular criteria set by each.
  • For certain AJAX requests, the server has to explicitly allow cross-origin resource sharing by setting the Access-Control-Allow-Origin response header.
  • If you want to allow clients all over the Internet to access your REST API through a browser, you’ll need to set some security headers

21 of 22

Practice Time

01-fetch-get

02-fetch-search

22 of 22