首页 > 解决方案 > 如何从 Github Api 获取 JSON 响应?

问题描述

我是编码新手,我被卡住了。我正在尝试从 GitHub 的 REST API 获取 JSON 响应。我正在使用外部脚本文件,但它不起作用。当我尝试在带有脚本标签的 HTML 中使用它时,它给出了一个错误。我尝试了一种用于在 fetch() 中验证令牌的方法,它给出了一个错误。它被称为“标题”我不知道。如果你们能帮忙,我会很高兴的。

HTML:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>GitHub API Trial</title>
</head>
<body>
    <script src="github.js"></script>
</body>
</html>

脚本:

getData();
const api_url = 'https://api.github.com/users/alisirri/repos';
async function getData() {
    const response = await fetch(api_repo_url,
        {
            headers: {
                authorization: "TOKEN"
            }
        }
    )
    console.log(await response.json());
}

标签: javascripthtml

解决方案


将 js 文件中的所有内容替换为:

const api_repo_url = "https://api.github.com/users/alisirri/repos";
fetch(api_repo_url, {
    headers: {
        authorization: "TOKEN",
    },
})
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    });

也不需要异步,因为 .then() 负责


推荐阅读