javascript - 获取随机用户 API

我正在尝试使用随机用户 API 获取一些数据,但看到“获取失败”错误。有人能指出我正确的方向来解决这个问题吗? TIA:)

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

await getUsers();

错误:

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

更新:原来我是在一个新的标签页/空白页中测试这个,它没有显示完整的错误是: “从原点‘null’获取‘...’的访问已被 CORS 策略阻止:请求的资源上不存在‘Access-Control-Allow-Origin’ header 。如果不透明的响应满足您的需求,请设置请求的模式为‘no-cors’以获取禁用 CORS 的资源。” 我现在安装了一个 Chrome 扩展程序来解决这个问题,尽管我确信可能有更好/更永久的方法来解决这个问题,我可能改天再试试!

最佳答案

你可以使用.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();

你也可以将它全部包装在一个异步函数中,因为 await 必须在异步函数中使用:

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

  console.log({ users });
})();

或使用您的原始语法:

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

getUsers().then((data) => console.log(data));

https://stackoverflow.com/questions/67369829/

相关文章:

c++ - 我可以在没有默认初始化的情况下初始化数组的 std::unique_ptr (我只想让它

ruby - "+1"给我的结果与 ruby​​ 中的 "+ 1"不同?

c++ - 如何在 cpp 中为 std::unordered_map 编写自定义 hash_

r - 如何将经过训练和测试的随机森林模型应用于 tidymodels 中的新数据集?

node.js - 如何从 bull js 中删除延迟的工作?

git - 无法访问 'https://github.com/Homebrew/brew/' : L

typescript - typescript 上的 Socket.io 附加属性不存在

amazon-ec2 - Tensorflow 安装在 AWS ec2 实例上终止

reactjs - 属性 'type' 在类型中缺失。但在类型 'Props' 中是必需的

flutter - 类型错误 : Cannot read property 'isSupported