JavaScript · API · Beginner
Redirects
Understand HTTP redirects and control how fetch handles them.
Quick topic start and explanations before exercises (exercises below):
Working with redirects in practice
#Redirect reference
#Exercises:
Follow a redirect
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// fetch /api/redirect/ and print final URL and status
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/redirect/`);
console.log(response.url);
console.log(response.status);
}
main();
Detect if a redirect happened
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const url = `${BASE_URL}/api/redirect/`;
// fetch and compare url vs response.url
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const url = `${BASE_URL}/api/redirect/`;
const response = await fetch(url);
console.log(response.url !== url);
}
main();
Compare temporary and permanent redirect
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// fetch both endpoints and print final url + status for each
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const r1 = await fetch(`${BASE_URL}/api/redirect/`);
console.log('Temporary:', r1.url, r1.status);
const r2 = await fetch(`${BASE_URL}/api/redirect/permanent/`);
console.log('Permanent:', r2.url, r2.status);
}
main();
Stop at redirect with manual mode
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// manual redirect
// follow redirect
// compare
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const manual = await fetch(`${BASE_URL}/api/redirect/`, { redirect: 'manual' });
console.log('Manual — type:', manual.type, 'status:', manual.status);
const follow = await fetch(`${BASE_URL}/api/redirect/`, { redirect: 'follow' });
console.log('Follow — url:', follow.url, 'status:', follow.status);
}
main();
Fetch data through a redirect
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// fetch through redirect and read the response body
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/redirect/`);
const data = await response.json();
console.log(data.count);
}
main();