To build robust web applications, frontend developers often need to interact with external APIs. APIs (Application Programming Interfaces) allow different applications to communicate and exchange data.
One common use case is fetching data from an API to display it on a web page. Let's say we want to retrieve user data from an API endpoint /users
.
Here's an example code snippet in JavaScript that demonstrates making a GET request to fetch user data from an API:
JAVASCRIPT
1// Make a GET request to retrieve user data
2
3const fetchUserData = async () => {
4 try {
5 const response = await fetch('https://api.example.com/users');
6 const data = await response.json();
7
8 console.log('User data:', data);
9 } catch (error) {
10 console.error('Error fetching user data:', error);
11 }
12};
13
14fetchUserData();
xxxxxxxxxx
16
// As a frontend developer, it's crucial to understand how to work with APIs to fetch and send data to the backend.
// Let's start by making a GET request to retrieve some data from an API.
const fetchUserData = async () => {
try {
const response = await fetch('https://api.example.com/users');
const data = await response.json();
console.log('User data:', data);
} catch (error) {
console.error('Error fetching user data:', error);
}
};
fetchUserData();
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment