• 在 Node.js 中发出 HTTP 请求的 5 种方法


    在 Node.js 中发出 HTTP 请求的 5 种方法

    学习如何在 Node.js 中发出 HTTP 请求可能会让人感到不知所措,因为有数十个可用的库,每个解决方案都声称比上一个更高效。一些库提供跨平台支持,而另一些库则关注捆绑包大小或开发人员体验。

    在这篇文章中,我们将探讨在 Node.js 中发出 HTTP 请求的五种最流行的方法,并为每种方法提供说明。

    首先,我们将介绍使用标准库的 HTTP 请求和 HTTPS 请求。之后,我们将展示如何使用 node-fetchAxiossuperagent 等替代方案。

    先决条件

    在开始之前,请确保我们的开发环境具备以下条件:

    • Node.js
    • 节点包管理器 (NPM)

    下面,我们将展示如何通过以下五种方法在 Node.js 中发出 HTTP 请求:

    • 标准库(HTTP 模块)
    • 标准库(HTTPS 模块)
    • Axios
    • node-fetch
    • superagent

    标准库(HTTP模块)

    Node.js 中的标准库配备了默认http模块。它可以发出 HTTP 请求,而无需添加大量外部包。然而,由于该模块是低级别的,因此它可能对开发人员更加友好。

    此外,我们需要使用异步流来对数据进行分块,因为 HTTP 请求的async/await功能不能与此库一起使用。然后需要手动解析响应数据。

    通常,我们会使用 HTTP 模块进行测试或演示,因为它不安全。

    这是使用http模块发出get请求的简单示例:

    const http = require('http');
    const options = {
      hostname: 'example.com',
      port: 80,
      path: '/',
      method: 'GET',
    };
    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        console.log(data);
      });
    });
    req.end();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    标准库(HTTPS模块)

    如果我们需要在 Node.js 中发出安全的 HTTPS 请求,您可以使用该https模块,该模块也内置于标准库中。用法与http模块非常相似,但增加了安全性。这是一个例子:

    const https = require('https');
    const options = {
      hostname: 'example.com',
      port: 443,
      path: '/',
      method: 'GET',
    };
    const req = https.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        console.log(data);
      });
    });
    req.end();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Axios

    Axios是一个流行的 Node.js HTTP 客户端库,它提供了一种更加用户友好且功能丰富的方式来发出 HTTP 请求。Axios 简化了错误处理并支持自动 JSON 解析和请求/响应拦截器等功能,使其成为许多 HTTP 请求场景的绝佳选择。

    在终端中输入以下命令使用 npm 安装 Axios

    npm install axios
    
    • 1

    以下代码片段展示了如何使用axios发出get请求:

    const axios = require('axios');
    axios.get('https://example.com')
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => {
        console.error(error);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    node-fetch

    node-fetch是专为 Node.js 定制的 JavaScript 库,可简化 HTTP 请求的生成。它提供了一种简单且基于 Promise 的方法,用于从 Internet 或服务器获取资源,例如 GETPOSTPUT DELETE 请求。它专为服务器端应用程序而设计,与 Fetch API 兼容,允许在客户端和服务器端环境之间轻松进行代码转换。

    此外,请注意,有用的扩展(例如重定向限制、响应大小限制和用于故障排除的显式错误)可与 node-fetch 一起使用。

    在终端中输入以下命令使用 npm 安装node-fetch

    npm install node-fetch
    
    • 1

    以下代码片段展示了如何使用 node-fetch 发出请求:

    const fetch = require('node-fetch');
    fetch('https://example.com')
      .then((response) => response.text())
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.error(error);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    superagent

    superagent是一个轻量级且灵活的 HTTP 客户端,支持 Promise 和回调式语法。它以其简单性和易用性而闻名。

    在终端中输入以下命令使用 npm 安装 superagent

    npm install superagent
    
    • 1

    以下代码片段展示了如何使用 superagent 发出请求:

    const request = require('superagent');
    request.get('https://example.com')
      .then((response) => {
        console.log(response.text);
      })
      .catch((error) => {
        console.error(error);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 相关阅读:
    Web前端开发技术课程大作业——南京旅游景点介绍网页代码html+css+javascript
    竞赛 深度学习实现行人重识别 - python opencv yolo Reid
    技术管理进阶——什么是管理者之体力、脑力、心力
    遥感原理与应用(一)什么是遥感?
    Django——模型层进阶
    kvm虚拟机压缩qcow2镜像空间
    flink集群部署
    【编程题】【Scratch三级】2021.06 计算成绩总和
    最小特权原则 (POLP)
    华为机试真题 Java 实现【猴子吃桃】
  • 原文地址:https://blog.csdn.net/qq_42880714/article/details/134472192