首页 > web前端 > js教程 > 正文

使用 Got 在 Node.js 中发出 HTTP 请求

WBOY
发布: 2024-08-28 06:06:02
原创
403 人浏览过

在 Node.js 中构建应用程序时,无论您是与外部 API 交互、获取数据还是在服务之间通信,发出 HTTP 请求都是一项基本任务。虽然 Node.js 具有用于发出请求的内置 http 模块,但它并不是最用户友好或功能丰富的解决方案。这就是像 Got 这样的图书馆的用武之地。

Got 是一个轻量级、功能丰富且基于 Promise 的 Node.js HTTP 客户端。它简化了发出 HTTP 请求的过程,提供了干净的 API、自动重试、对流的支持等等。在本文中,我们将探讨如何使用 Got 来发出 HTTP 请求和处理错误。

为什么选择 Got 来处理 HTTP 请求?

在深入研究代码之前,了解为什么 Got 是许多开发人员的首选非常重要:

  • 简单的 API: Got 提供了一个干净直观的 API,可以轻松执行各种类型的 HTTP 请求。
  • 基于 Promise: Got 完全基于 Promise,允许您使用 async/await 语法来获得更清晰、更易读的代码。
  • 自动重试:Got 可以在网络故障或其他问题时自动重试请求,这对于提高应用程序的可靠性特别有用。
  • 对流的支持:支持流,这对于下载大文件或处理块数据非常有用。
  • 可定制: Got 是高度可定制的,提供修改标头、查询参数、超时等选项。

安装Got

要开始使用 Got,您首先需要将其安装到 Node.js 项目中。如果您尚未设置 Node.js 项目,请按照以下步骤操作:

  1. 初始化您的项目:打开终端并为您的项目创建一个新目录:
   mkdir got-http-requests
   cd got-http-requests
   npm init -y
登录后复制

此命令创建一个新的项目目录并使用 package.json 文件对其进行初始化。

  1. 安装 Got: 接下来,使用 npm 安装 Got:
   npm install got
登录后复制

Got 现已添加到您的项目中,您可以开始使用它来发出 HTTP 请求。

使用 Got 发出 HTTP 请求

Got 可以轻松执行各种类型的 HTTP 请求。让我们来看看一些常见的用例。

1. 发出基本的 GET 请求

GET 请求是最常见的 HTTP 请求类型,通常用于从服务器检索数据。使用 Got,发出 GET 请求非常简单:

const got = require('got');

(async () => {
    try {
        const response = await got('https://jsonplaceholder.typicode.com/posts/1');
        console.log('GET Request:');
        console.log(response.body);
    } catch (error) {
        console.error('Error in GET request:', error.message);
    }
})();
登录后复制
  • 说明:
  • 端点: https://jsonplaceholder.typicode.com/posts/1 是一个测试 API,返回 ID 为 1 的帖子的详细信息。
  • Got 语法: got(url) 函数向指定的 URL 发送 GET 请求。响应被作为承诺处理,允许我们使用await来等待响应。
  • 响应: 响应正文将记录到控制台,其中将包含帖子的 JSON 数据。

2. 发出 POST 请求

POST 请求用于将数据发送到服务器,通常用于创建新资源。使用 Got,您可以轻松地在 POST 请求中发送 JSON 数据:

const got = require('got');

(async () => {
    try {
        const response = await got.post('https://jsonplaceholder.typicode.com/posts', {
            json: {
                title: 'foo',
                body: 'bar',
                userId: 1
            },
            responseType: 'json'
        });
        console.log('POST Request:');
        console.log(response.body);
    } catch (error) {
        console.error('Error in POST request:', error.message);
    }
})();
登录后复制
  • 说明:
  • 端点: https://jsonplaceholder.typicode.com/posts 用于在服务器上创建新帖子。
  • JSON 数据: Got 请求中的 json 选项允许您指定要发送的数据。在这里,我们将发送一篇带有标题、正文和用户 ID 的新帖子。
  • 响应: 服务器的响应(包括与新 ID 一起发送的数据)将记录到控制台。

3. 处理错误

HTTP 请求期间可能会出现网络问题或服务器错误。 Got 提供了一种简单的方法来处理这些错误:

const got = require('got');

(async () => {
    try {
        const response = await got('https://nonexistent-url.com');
        console.log(response.body);
    } catch (error) {
        console.error('Error handling example:', error.message);
    }
})();
登录后复制
  • 说明:
  • 不存在的 URL: 此示例尝试向不存在的 URL 发出 GET 请求。
  • 错误处理:当请求失败时,Got会自动抛出错误。 catch 块捕获此错误并将错误消息记录到控制台。

Got 的高级功能

Got 不仅仅是发出简单的 GET 和 POST 请求。它配备了多项高级功能,可以帮助您处理更复杂的场景。

1. 自定义请求选项

Got 允许您通过设置标头、查询参数、超时等来自定义请求:

const got = require('got');

(async () => {
    try {
        const response = await got('https://jsonplaceholder.typicode.com/posts/1', {
            headers: {
                'User-Agent': 'My-Custom-Agent'
            },
            searchParams: {
                userId: 1
            },
            timeout: 5000
        });
        console.log('Customized Request:');
        console.log(response.body);
    } catch (error) {
        console.error('Error in customized request:', error.message);
    }
})();
登录后复制
  • Explanation:
  • Headers: You can set custom headers using the headers option. Here, we set a custom User-Agent.
  • Query Parameters: The searchParams option allows you to add query parameters to the URL.
  • Timeout: The timeout option sets the maximum time (in milliseconds) the request can take before throwing an error.

2. Streaming with Got

Got supports streaming, which is useful for handling large data or working with files:

const fs = require('fs');
const got = require('got');

(async () => {
    const downloadStream = got.stream('https://via.placeholder.com/150');
    const fileWriterStream = fs.createWriteStream('downloaded_image.png');

    downloadStream.pipe(fileWriterStream);

    fileWriterStream.on('finish', () => {
        console.log('Image downloaded successfully.');
    });
})();
登录后复制
  • Explanation:
  • Streaming: The got.stream(url) function initiates a streaming GET request. The data is piped directly to a writable stream, such as a file.
  • File Writing: The fs.createWriteStream() function is used to write the streamed data to a file.

Making HTTP Requests in Node.js with Got

Download the source code here.

Conclusion

Got is a versatile and powerful library for making HTTP requests in Node.js. It simplifies the process of interacting with web services by providing a clean and intuitive API, while also offering advanced features like error handling, timeouts, and streams. Whether you’re building a simple script or a complex application, Got is an excellent choice for handling HTTP requests.

By using Got, you can write cleaner, more maintainable code and take advantage of its robust feature set to meet the needs of your application. So the next time you need to make an HTTP request in Node.js, consider using Got for a hassle-free experience.

Thanks for reading…

Happy Coding!

The post Making HTTP Requests in Node.js with Got first appeared on Innovate With Folasayo.

The post Making HTTP Requests in Node.js with Got appeared first on Innovate With Folasayo.

以上是使用 Got 在 Node.js 中发出 HTTP 请求的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!