How can I get JSON response from Github Api?

I’m new at coding and I’m stuck. I’m trying to take JSON response from GitHub’s REST API. I’m using external script file but it’s not working. When I tried to use it in HTML with the script tag it’s giving an error. I tried a way that is used for authenticating the token in fetch() it gives an error about that. It’s called "header" I don’t know about that. I will be happy if you guys help.

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>

Script:

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());
}

>Solution :

Replace everything in the js file with this:

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);
    });

No need for async either as .then() takes care of that

Leave a Reply