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 リクエストを作成し、エラーを処理する方法を説明します。

HTTP リクエストに Got を選択する理由

コードに入る前に、なぜ Got が多くの開発者にとって好まれる選択肢なのかを理解することが重要です。

  • シンプルな API: Got は、さまざまな種類の HTTP リクエストを簡単に実行できる、クリーンで直感的な API を提供します。
  • Promise ベース: Got は完全に Promise ベースであるため、async/await 構文を使用して、よりクリーンで読みやすいコードを実現できます。
  • 自動再試行: Got は、ネットワーク障害やその他の問題が発生した場合にリクエストを自動的に再試行できます。これは、アプリケーションの信頼性を向上させるのに特に役立ちます。
  • ストリームのサポート: Got はストリーミングをサポートしています。これは、大きなファイルのダウンロードや、チャンク内のデータの操作に役立ちます。
  • カスタマイズ可能: Got は高度にカスタマイズ可能で、ヘッダー、クエリ パラメーター、タイムアウトなどを変更するオプションがあります。

Gotのインストール

Got を使い始めるには、まず Node.js プロジェクトに Got をインストールする必要があります。 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 は、ID 1 の投稿の詳細を返すテスト API です。
  • Got 構文: got(url) 関数は、指定された URL に GET リクエストを送信します。応答は Promise として処理されるため、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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!