Homework & Coding Practice
Homework/Practice Coding Assignment (20-min)
Step-by-Step Procedure
Write a Node.js Script Using async/await to Fetch Data from a Public API:
Use a public API, such as the JSONPlaceholder API:
https://jsonplaceholder.typicode.com/posts.Create a file named
asyncAwaitExample.js:javascript코드 복사const fetch = require('node-fetch'); const fetchData = async () => { 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('First post:', data[0]); } catch (err) { console.error('Error fetching data:', err.message); } }; fetchData();Steps:
Install
node-fetchif not already installed:bash코드 복사npm install node-fetchRun the script:
bash코드 복사node asyncAwaitExample.js
Expected Output:
Logs the first post from the API.
Identify and Handle Potential Errors:
Modify the script to:
Check for invalid URLs.
Handle unexpected API response formats.
Example Error Handling:
javascript코드 복사const fetchData = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/invalid'); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const data = await response.json(); console.log(data); } catch (err) { console.error('Error:', err.message); } }; fetchData();
Test the Script:
Run it with valid and invalid URLs to observe the error-handling behavior.
Last updated