Search code examples
javascriptasync-awaitfetch

Fetch random user API


I'm trying to use the random user API to fetch some data, but seeing a "Failed to fetch" error. Could someone point me in the right direction for how to fix this? TIA :)

async function getUsers() {
  let users = await fetch('https://randomuser.me/api/?results=2');
  let data = await users.json();
}

await getUsers();

Errors:

GET https://randomuser.me/api/?results=5 net::ERR_FAILED
Uncaught (in promise) TypeError: Failed to fetch

Promise:

Promise {<pending>}__proto__: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: TypeError: Failed to fetch

async-await-fetch-fail1

UPDATE: it turns out I was testing this in a new tab/blank page, which does not show the full error which was: "Access to fetch at '...' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." I installed a Chrome extension to resolve this for now, although I'm sure there's probably a better/more permanent way to fix this, and I might try that some other day!


Solution

  • You could use .then()

    function getUsers() {
        fetch("https://randomuser.me/api/?results=2")
          .then((results) => {
            return results.json();
          })
          .then((data) => {
            console.log(data);
            // Access your data here
          });
      }
      
    getUsers();

    And you could also wrap it all in an async function as await must be used inside an async function:

    (async function () {
      const users = await fetch("https://randomuser.me/api/?results=2")
        .then((response) => response.json())
        .then((data) => {
          return data;
        });
    
      console.log({ users });
    })();

    OR using your original syntax:

    async function getUsers() {
      const users = await fetch("https://randomuser.me/api/?results=2");
      return users.json();
    }
    
    getUsers().then((data) => console.log(data));