简体   繁体   中英

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

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

I tested your code and looks like the headers are unnecessary

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM