Homework & Coding Practice

Homework/Practice Coding Assignment (20-min)

Step-by-Step Procedure

  1. 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:

      1. Install node-fetch if not already installed:

        bash코드 복사npm install node-fetch
      2. Run the script:

        bash코드 복사node asyncAwaitExample.js
    • Expected Output:

      • Logs the first post from the API.

  2. 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();
  3. Test the Script:

    • Run it with valid and invalid URLs to observe the error-handling behavior.

Last updated