【发布时间】:2020-09-01 12:23:03
【问题描述】:
我想知道如何使用 deno 从其他服务器和 API 获取数据?文档中的所有内容都教我如何制作 http 服务器和从本地源读取文件。但是我找不到任何有用的信息来阅读网络上的内容。
如何从 Stripe API 读取 JSON 数据?或者如果我想读取一个带有文本的 HTML 文件?
感谢您的宝贵时间!
【问题讨论】:
标签: deno
我想知道如何使用 deno 从其他服务器和 API 获取数据?文档中的所有内容都教我如何制作 http 服务器和从本地源读取文件。但是我找不到任何有用的信息来阅读网络上的内容。
如何从 Stripe API 读取 JSON 数据?或者如果我想读取一个带有文本的 HTML 文件?
感谢您的宝贵时间!
【问题讨论】:
标签: deno
我只是给你一个获取 Github 存储库的 GET 请求示例。
您可以根据需要更改 URL 和请求配置。
在下面给出的代码中,我调用了 Github 的另一个 API。通过使用fetch() 方法,您可以做到这一点。
fetch()方法首先将URL作为第一个参数,下一个参数是RequestInit,它接受请求方法类型、headers、body 等,最后返回该 API 调用的 JSON 响应。
const githubResponse = async (): Promise<any> => {
const response = await fetch("https://api.github.com/search/repositories?q=android", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
return response.json(); // For JSON Response
// return response.text(); // For HTML or Text Response
}
console.log(await githubResponse());
我已经在一个名为 Testing.ts 的ts 文件中编写了上述代码。所以,你可以通过下面给出的命令运行上面的代码:
deno run --allow-net Testing.ts
接下来,我给你一个示例POST请求代码:
const githubResponse = async (): Promise<any> => {
const body: URLSearchParams = new URLSearchParams({
q: "AvijitKarmakar",
});
const response = await fetch("https://api.github.com/search/repositories", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: body
});
return response.json();
// return response.text(); // For HTML or Text Response
}
console.log(await githubResponse());
可以看到我创建了一个body对象,并通过body参数传入RequestInit,同时也将请求方法类型改为POST强>.
【讨论】:
您需要执行 HTTP 请求,因为在 Deno 中您使用 fetch,浏览器使用的 Web API 相同。
读取 JSON 响应:
const res = await fetch('https://api.stripe.com');
const data = await res.json();
如果你想要 HTML:
const res = await fetch('https://example.com');
const html = await res.text();
// Now you can use some HTML parsing lib
fetch 需要 --allow-net 标志。
【讨论】: