Deno - 如何从遥远的 API 或 URL 获取数据?

Deno - How to fetch data from distant API or URL?

我想知道如何使用 deno 从其他服务器和 API 获取数据?文档中的所有内容都教会了我如何制作 http 服务器和从本地源读取文件。但是在网络上看书找不到有用的东西

如何从 Stripe API 中读取 JSON 数据?或者,如果我想读取一个包含文本的 HTML 文件 ?

感谢您的宝贵时间!

您需要执行 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 标志。

Deno 力求尽可能接近现有的浏览器API。

也就是说,你可以使用fetch。示例:

// fetch-kitten.ts
fetch("https://placekitten.com/200/300").then(async (d) =>
  Deno.writeFile("kitten.jpg", new Uint8Array(await d.arrayBuffer()))
);
命令行界面:
deno run --allow-net --allow-write fetch-kitten.ts

Reference

我只是给你一个获取 Github.

存储库的 GET 请求的例子

您可以根据需要更改 URL 和请求配置。

在下面给出的代码中,我调用了 Github 的另一个 API。通过使用 fetch() 方法,您可以做到这一点。

fetch()方法首先将URL作为第一个参数,下一个参数是RequestInit,它采用请求方法类型headersbody 等,最后返回 JSON 那个 API 调用的响应。

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.tsts 文件中。因此,您可以通过下面给出的命令 运行 上面的代码:

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.