1707404727

Requesting Remote Data with Fetch


Use the Fetch API, which allows you to make requests and manipulate the response. To make a simple request, pass a URL as a fetch parameter, which returns the response as a promise. The following example requests the URL, parses the JSON response, and logs the response to the console: ```js const url = 'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY'; fetch(url) .then(response => response.json()) .then(data => console.log(data)); ``` Alternately, use the async/await syntax with fetch: ```js const url = 'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY'; async function fetchRequest() { const response = await fetch(url); const data = await response.json(); console.log(data); } fetchRequest(); ``` The Fetch API provides a means for sending and retrieving data from a remote source. When working in a web browser environment, this means that data can be retrieved without refreshing the page. As a web user, you may experience these types of requests frequently. The Fetch API can be used to: * Load additional items in a social media feed * Form autocomplete suggestions * “Like” a social media post * Update form field values based on a previous response * Submit a form without navigating away from the page * Add an item to a shopping cart As you may imagine, the list can go on and on. When using fetch, you can handle errors based on the server’s status response. In async/await: ```js async function fetchRequestWithError() { const response = await fetch(url); if (response.status >= 200 && response.status < 400) { const data = await response.json(); console.log(data); } else { // Handle server error // example: INTERNAL SERVER ERROR: 500 error console.log(`${response.statusText}: ${response.status} error`); } } ``` Errors can be handled similarly when using the the JavaScript then promise syntax: ```js fetch(url) .then((response) => { if (response.status >= 200 && response.status < 400) { return response.json(); } else { // Handle server error // example: INTERNAL SERVER ERROR: 500 error console.log(`${response.statusText}: ${response.status} error`); } }) .then((data) => { console.log(data) }).catch(error) => { // Generic error handler console.log(error); }; ``` Leave a comment or chat to me [<span style="color: blue;">here</span>](https://chat-to.dev/chat?q=world-nodejs) if you liked the post

To comment this publication you need to be logged in.