Client-Side Templating & Fetch
CS 396: �Introduction to Web Development
Spring, 2022
Outline
Outline
Recall: Server-Side Templates
In HW2, the Photo App interface was generated on the server. Specifically:
Next Two Weeks: Client-Side Templating
In HW4, we will practice building client-side templates. Specifically:
�Example: https://www.instagram.com/
Outline
1. Intro to AJAX
AJAX
7
1. Intro to Fetch
JavaScript’s Fetch API
8
1. How Fetching a Web Resource Works
fetch(url)
.then(response => {
// handle the response
})
.catch(err => {
// handle the error
});
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
2. What is a Promise?
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
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();
Outline
Error Handling
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);
});
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);
});
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();
Outline
Cross-Origin Resource Sharing (CORS)
Practice Time
01-fetch-get
02-fetch-search
If time: get started on HW4!