javascript - 如何从 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());
}
解决方案
将 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() 负责
推荐阅读
- excel - 仅针对特定用户名打开工作簿时自动运行的宏
- android - 等待凌空响应,然后更新 ListView
- clojurescript - 如何在 ClojureScript 中编写不可知的 JavaScript 库?
- c# - 如何在 selenium c# 中为异常截屏
- javascript - 在javascript中用reg exp替换'&'字符
- actions-on-google - Actions on Google:测试版被拒绝
- javascript - 监视 vuejs 中动态变化的对象的变化
- angular-cli - ng --version 显示 Angular CLI: 1.5.4 即使在升级后
- database - Netezza 性能优化
- node.js - 从 gitlab 安装 NPM 包不会仅在 CI 上下载所有 repo 文件