request-promise-native 的替代品

Alternatives to request-promise-native

我一直在寻找实现基本 HTTP 方法的现代模块,例如 Node.js 中的 GET、POST。

我猜最受欢迎的是 request. The async/await version of it is called request-promise-native

最近我了解到这些模块正在 deprecated。那么,我可以使用哪些基于 async/await 范式的现代替代方案?

关于 request 的同一个 github 问题,还有另一个 link 讨论了替代方案。你可以看到他们 here。它清楚地解释了不同的类型和它们的风格 (promise/callback)。

考虑到另一个选择,我建议使用节点本机 http 模块。

import * as http from 'http';

async function requestPromise(path: string) {
    return new Promise((resolve, reject) => {
        http.get(path, (resp) => {
            let data = '';

            resp.on('data', (chunk) => {
                data += chunk;
            });

            resp.on('end', () => {
                resolve(data);
            });

        }).on("error", (error) => {
            reject(error);
        });
    });
}

(async function () {
    try {
        const result = await requestPromise('http://www.google.com');
        console.log(result);
    } catch (error) {
        console.error(error);
    }
})();

我强烈建议在它后面使用 node-fetch. It is based on the fetch API in modern browsers. Not only is it promise-based it also has an actual standard

您不使用 fetch 的唯一原因是您不喜欢 API。然后我建议使用像 axios or superagent.

这样的跨平台的东西

我个人发现在服务器和浏览器上使用相同的 API 可以简化可维护性并提供代码重用的潜力。

Got好甜

"Got是因为流行的请求包臃肿而创建的。 此外,Got 是完全用 TypeScript 编写的,并且是主动的 已维护。”- https://www.npmjs.com/package/got#faq