JavaScriptには、サーバー側のリソースとの間でデータを送受信するために使用できるHTTPリクエストを作成するための優れたモジュールとメソッドがあります。この記事では、JavaScriptでHTTPリクエストを作成するためのいくつかの一般的な方法を見ていきます。
Ajax
Ajaxは、非同期HTTPリクエストを作成する従来の方法です。データは、HTTP POSTメソッドを使用して送信し、HTTPGETメソッドを使用して受信できます。見て、GET
リクエストしてみましょう。JSON形式でランダムデータを返す開発者向けの無料のオンラインRESTAPIであるJSONPlaceholderを使用します。
AjaxでHTTP呼び出しを行うには、新しいXMLHttpRequest()
メソッドを初期化し、URLエンドポイントとHTTPメソッド(この場合はGET)を指定する必要があります。最後に、このopen()
メソッドを使用してHTTPメソッドとURLエンドポイントを結び付け、send()
メソッドを呼び出してリクエストを実行します。
イベントが発生したXMLHTTPRequest.onreadystatechange
ときに呼び出されるイベントハンドラーを含むプロパティを使用して、コンソールへのHTTP応答をログに記録しますreadystatechanged
。

const Http = new XMLHttpRequest(); const url="//jsonplaceholder.typicode.com/posts"; Http.open("GET", url); Http.send(); Http.onreadystatechange = (e) => { console.log(Http.responseText) }
ブラウザコンソールを表示すると、JSON形式でデータの配列が返されます。しかし、要求が行われたかどうかをどのように知ることができますか?言い換えれば、Ajaxで応答を処理するにはどうすればよいですか?
onreadystatechange
プロパティには、二つの方法があり、readyState
そしてstatus
それは、私たちは私たちの要求の状態を確認することができます。

readyState
が4に等しい場合は、要求が完了したことを意味します。readyState
施設には、5つのレスポンスを持っています。詳細については、こちらをご覧ください。
JavaScriptを使用してAjax呼び出しを直接行う以外に$.Ajax
、jQueryメソッドなどのHTTP呼び出しを行うより強力なメソッドが他にもあります。それらについては今から説明します。
jQueryメソッド
jQueryには、HTTPリクエストを簡単に処理するための多くのメソッドがあります。これらのメソッドを使用するには、プロジェクトにjQueryライブラリを含める必要があります。
$ .ajax
jQuery Ajaxは、HTTP呼び出しを行うための最も簡単なメソッドの1つです。

$ .ajaxメソッドは多くのパラメーターを取りますが、そのうちのいくつかは必須で、その他はオプションです。これには、2つのコールバックオプションsuccess
とerror
、受信した応答を処理するためのオプションが含まれています。
$ .getメソッド
$ .getメソッドは、GETリクエストを実行するために使用されます。エンドポイントとコールバック関数の2つのパラメーターを取ります。

$ .post
この$.post
方法は、サーバーにデータを投稿するもう1つの方法です。url
、、投稿するデータ、およびコールバック関数の3つのパラメーターを取ります。

$ .getJSON
この$.getJSON
メソッドは、JSON形式のデータのみを取得します。とurl
コールバック関数の2つのパラメーターを取ります。

jQueryには、リモートサーバーにデータを要求または投稿するためのこれらすべてのメソッドがあります。ただし、実際には、これらすべてのメソッドを1つにまとめることができ$.ajax
ます。以下の例に示すように、メソッドです。

フェッチ
fetch
は、非同期リクエストを作成できる新しい強力なWebAPIです。実際、これfetch
はHTTPリクエストを作成するための最良かつ私のお気に入りの方法の1つです。ES6の優れた機能の1つである「Promise」を返します。ES6に慣れていない場合は、この記事でES6について読むことができます。Promiseを使用すると、非同期リクエストをよりスマートに処理できます。fetch
技術的にどのように機能するかを見てみましょう。

このfetch
関数は、endpoint
URLという1つの必須パラメーターを取ります。以下の例のように、他のオプションのパラメーターもあります。

ご覧のとおりfetch
、HTTPリクエストを作成するための多くの利点があります。詳細については、こちらをご覧ください。さらに、フェッチ内には、axiosなど、サーバー側との間でリクエストを送受信できるようにする他のモジュールやプラグインがあります。
Axios
Axios is an open source library for making HTTP requests and provides many great features. Let’s have a look at how it works.
Usage:
First, you’d need to include Axios. There are two ways to include Axios in your project.
First, you can use npm:
npm install axios --save
Then you’d need to import it
import axios from 'axios'
Second, you can include axios using a CDN.
Making a Request with axios:
With Axios you can use GET
and POST
to retrieve and post data from the server.
GET:

axios
takes one required parameter, and can take a second optional parameter too. This takes some data as a simple query.
POST:

Axios returns a “Promise.” If you’re familiar with promises, you probably know that a promise can execute multiple requests. You can do the same thing with axios and run multiple requests at the same time.

Axios supports many other methods and options. You can explore them here.
Angular HttpClient
Angular has its own HTTP module that works with Angular apps. It uses the RxJS library to handle asynchronous requests and provides many options to perform the HTTP requests.
Making a call to the server using the Angular HttpClient
To make a request using the Angular HttpClient, we have to run our code inside an Angular app. So I created one. If you’re not familiar with Angular, check out my article, learn how to create your first Angular app in 20 minutes.
The first thing we need to do is to import HttpClientModule
in app.module.ts

Then, we have to create a service to handle the requests. You can easily generate a service using Angular CLI.
ng g service FetchdataService
Then, we need to import HttpClient in fetchdataService.ts
service and inject it inside the constructor.

And in app.component.ts
import fetchdataService
//import import { FetchdataService } from './fetchdata.service';
Finally, call the service and run it.
app.component.ts:

You can check out the demo example on Stackblitz.
Wrapping Up
We’ve just covered the most popular ways to make an HTTP call request in JavaScript.
Thank you for your time. If you like it, clap up to 50, click follow, and reach out to me on Twitter.
By the way, I’ve recently worked with a strong group of software engineers for one of my mobile applications. The organization was great, and the product was delivered very quickly, much faster than other firms and freelancers I’ve worked with, and I think I can honestly recommend them for other projects out there. Shoot me an email if you want to get in touch — [email protected].