在 Node.js 中发送 HTTP 请求

发布于 2022-09-11 13:56:58 字数 2232 浏览 207 评论 0

Node.js 有一个 内置的 HTTP 库 ,可以让您在没有外部模块的情况下发出 HTTP 请求。 唯一的缺点是 API 有点过时:它依赖于流,不支持 Promise。以下是如何发出 HTTP 请求 httpbin.org 使用 Nodejs 的 http 模块:

const http = require('http');

// `res` is an instance of Node's built-in `ServerResponse` class:
// https://nodejs.org/api/http.html#http_class_http_serverresponse
const res = await new Promise(resolve => {
  http.get('http://httpbin.org/get?answer=42', resolve);
});

// A ServerResponse is a readable stream, so you need to use the
// stream-to-promise pattern to use it with async/await.
let data = await new Promise((resolve, reject) => {
  let data = '';
  res.on('data', chunk => data += chunk);
  res.on('error', err => reject(err));
  res.on('end', () => resolve(data));
});

data = JSON.parse(data);
data.args; // { answer: 42 }

您需要了解 Node 的 HTTP 库的一些细微差别:

  1. 支持 https:// 网址。 你会得到一个 Protocol "https:" not supported. Expected "http:" 如果你调用出错 http.request() 带有 HTTPS URL。 你需要使用 require('https').request() 反而。
  2. http.request() 具有非标准 回调 签名:没有错误参数。 只是 http.request(url, function callback(res) {}),由于这个非标准的回调签名,你不能使用 http.request()_ promisify() 功能

备择方案

由于 API 中存在这些粗糙的边缘,大多数开发人员不会使用 Node.js 的 HTTP 库来发出请求。 我们建议改用 Axios 。下面是如何使用 Axios 发出上述 HTTP 请求。

const axios = require('axios');

const res = await axios.get('https://httpbin.org/get?answer=42');

res.data.args; // { answer: 42 }

Axios 使 HTTP 请求比使用 Node.js 的内置库更干净。 另外由于 Axios 请求是 Promise,您可以 使用以下方法处理错误 catch()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

文章
评论
28 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文