Fetch request not returning any data in console, or on front end

Viewed 740

When I submit my form, I am not returning any data, not even in my console. I am trying to return details from WHOIS regarding the URL that is searched, and am getting nothing back.

Can anyone provide any advice as to why this might be the case?

Here is my front end script tag, after my form:

document.getElementById('search').addEventListener('submit', function(e) { e.preventDefault(); getDetails(); })
async function getDetails(url = `http://localhost:3000/lookup/${url}`, data = {}) {
  return new Promise(function (resolve, reject) {
    fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'text/html'
      },
      body: JSON.stringify(data)
      }).then(async response => {
        if (response.ok) {
          response.json().then(json => resolve(json))
          console.log(data);
        } else {
          response.json().then(json => reject(json))
        }
      }).catch(async error => {
        reject(error)
      })
  })
} 

On my express backend I am using req.params.url if that helps provide any context at all...

My Status Code is 200, and all appears to be normal in the Headers tab...

2 Answers

You have a mix of promise and async syntax, which is confusing, let's translate it first by unpicking the promise and then into await (if you can use async then do, it's easer than Promise/then):

document.getElementById('search').addEventListener(
    'submit', 
    function(e) { 
        e.preventDefault(); 
        getDetails(); 
    });

async function getDetails(url = `http://localhost:3000/lookup/${url}`, data = {}) 
{
    // Fetch will throw an exception if it can't connect to the service
    const response = await fetch(url, {
        method: 'GET',
        headers: { 'Content-Type': 'text/html' },
        body: JSON.stringify(data)
    });

    if (response.ok)
        return await response.json();
    
    // We could connect but got an error back from the service
    // There may not be a response body, so response.json() or .body() might crash
    throw new Error(`Error from server ${response.status}: ${response.statusText}`;
    
    // We don't need catch, as any exception in an await will cascade up anyway
} 

This makes it much more readable, and it's apparent that getDetails doesn't make any changes itself, it just returns the JSON from the service. The fix needs to be in the event listener - it needs to do something with that result:

document.getElementById('search').addEventListener(
    'submit', 
    async e => { 
        e.preventDefault(); 
        const searchResult = await getDetails();

        // Do something to show the results, populate #results
        const resultsElement = document.getElementById('results');
        resultsElement.innerText = JSON.stringify(searchResult);
    });

You are mis-using async/await. Try this:

async function getDetails(url = `http://localhost:3000/lookup/${url}`, data = {}) {
  const response = await fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'text/html'
    },
    body: JSON.stringify(data)
  });
  const json = await response.json();
  if (response.ok) {
    console.log(json);
    return json;
  } else {
     throw new Error(json);
  }
}

In essence await is a replacement for then (but you can only use it in functions marked with async).

Related