The Fetch API is a modern JavaScript standard for making HTTP requests. It is promise-based, allowing for simpler and more powerful interactions compared to older methods like XMLHttpRequest
.
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));
Resource: Fetch API - MDN Web Docs
Asynchronous API calls prevent your code from blocking while waiting for a response, maintaining a responsive UI.
Resource: Understanding Asynchronous JavaScript
Promises handle asynchronous operations by representing an operation that will complete in the future.
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));
Resource: JavaScript Promises - MDN Web Docs
GET requests retrieve data from a server.
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));
Resource: How to Use the JavaScript Fetch API to Get Data
Proper error handling in fetch requests is crucial.
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Resource: Error Handling with Fetch
Send additional information with your requests using headers.
fetch('https://jsonplaceholder.typicode.com/posts', {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Resource: Fetch API Headers - MDN Web Docs
Async/await makes your asynchronous code cleaner and more readable.
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
Resource: JavaScript Fetch with Async/Await
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is text-based and follows a syntax inspired by JavaScript object notation, which makes it familiar to JavaScript developers.
JSON data is represented in key-value pairs. Here’s a basic example:
{
"name": "John",
"age": 30,
"isStudent": false,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"city": "Anytown"
}
}
Resource: JSON - MDN Web Docs
To convert a JSON string into a JavaScript object, use JSON.parse()
:
const jsonResponse = '{"name": "John", "age": 30}';
const user = JSON.parse(jsonResponse);
console.log(user.name); // Output: John
Resource: JSON.parse() - MDN Web Docs
To convert a JavaScript object into a JSON string, use JSON.stringify()
:
const userObject = { name: "John", age: 30 };
const jsonString = JSON.stringify(userObject);
console.log(jsonString); // Output: '{"name":"John","age":30}'
Resource: JSON.stringify() - MDN Web Docs
Callbacks:
function getUser(userId, callback) {
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(response => response.json())
.then(user => callback(user))
.catch(error => console.error('Error:', error));
}
getUser(1, user => {
console.log('User fetched:', user);
});
Promises:
function getUser(userId) {
return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(response => response.json())
.then(user => {
console.log('User fetched:', user);
return user;
})
.catch(error => console.error('Error:', error));
}
getUser(1);
Async/Await:
async function getUser(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
const user = await response.json();
console.log('User fetched:', user);
} catch (error) {
console.error('Error:', error);
}
}
getUser(1);
Resource: Async/Await - MDN Web Docs
async function safeGetUser(userId) {
try {
const user = await getUser(userId);
return user;
} catch (error) {
console.error('Failed to fetch user:', error);
return { name: 'Default User', age: 0 };
}
}
Resource: Error Handling in Async Functions
Mastering HTTP requests and handling JSON data is crucial for modern web development. Up next, we’ll explore more HTTP methods like POST, PUT, and DELETE.
These combined lessons provide a comprehensive guide to making HTTP requests with JavaScript and handling JSON data, essential skills for any web developer.