Requests

It allows fetching data from servers or APIs (for data, files, authentication, etc.) and sending HTTP/HTTPS requests using XML objects or modern API systems. This works along with the HTTP protocol to communicate with sites over the web.

  • The fetch() function creates a request object that can be sent to an endpoint. Then it returns a promise that ultimately resolves to a response object, which contains the status of the promise with information the site sent back

fetch('https://www.example.com')
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error('Error:', error);
  });

  • Here we find a structured example of using the fetch() function for a GET petition, with response and error handling

const makeQuery = (query) => {
  const endpoint = url + query;
  fetch(endpoint, { cache: 'no-cache' })
    .then(response => {
      if (response.ok){  // Check 200 status code
        return response.json();  // Return response as json
      }
      throw new Error('Request failed!');  // Handle response error
    }, networkError => {
      console.log(networkError.message)
    }).then(jsonResponse => {
      console.log(jsonResponse)
    });
}

  • Now we find an example for a POST petition, with response and error handling

const makeQuery = (query) => {
  const endpoint = url + query;
  fetch(endpoint, {
      method: 'POST',  // Specify method to use
      body: JSON.stringify({id:'200'}) // Send the body of the petition
    }).then(response => {
      if (response.ok){  // Check 200 status code
        return response.json();  // Return response as json
      }
      throw new Error('Request failed!');  // Handle response error
    }, networkError => {
      console.log(networkError.message)
    }).then(jsonResponse => {
      console.log(jsonResponse)
    });
}

  • We can also change the structure to use the async and await keywords to manage petitions

const getData =async () => {
  try {
    const response = await fetch('https://www.example.com/')
    if (response.ok){  // Check 200 status code
      const jsonResponse = await response.json();  // Return response as json
    }
    throw new Error('Request failed!');  // Handle response error
  }catch (error){
    console.log(error);
  }
}
console.log(getData())

Last updated