ל- JavaScript יש מודולים ושיטות נהדרות לבצע בקשות HTTP בהן ניתן להשתמש כדי לשלוח או לקבל נתונים ממשאב בצד השרת. במאמר זה נבחן כמה דרכים פופולריות להגיש בקשות HTTP ב- JavaScript.
אייאקס
Ajax היא הדרך המסורתית להגיש בקשת HTTP אסינכרונית. ניתן לשלוח נתונים בשיטת HTTP POST ולקבל אותם בשיטת HTTP GET. בואו נסתכל ונגיש GET
בקשה. אני אשתמש ב- JSONPlaceholder, REST API מקוון בחינם למפתחים שמחזיר נתונים אקראיים בפורמט JSON.
כדי לבצע שיחת HTTP ב- Ajax, עליך לאתחל XMLHttpRequest()
שיטה חדשה , לציין את נקודת הקצה של ה- URL ואת שיטת ה- HTTP (במקרה זה GET). לבסוף, אנו משתמשים open()
בשיטה כדי לקשור את שיטת ה- HTTP ונקודת הקצה של ה- URL יחד וקוראים send()
לשיטה להפעיל את הבקשה.
אנו רושמים את תגובת ה- HTTP למסוף באמצעות XMLHTTPRequest.onreadystatechange
המאפיין המכיל את מטפל האירועים אליו יש לקרוא בעת הפעלת 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. אבל איך נדע אם הבקשה נעשית? במילים אחרות, איך נוכל להתמודד עם התגובות עם אייאקס?
onreadystatechange
יש הרכוש שתי שיטות, readyState
ואת status
אשר מאפשר לנו לבדוק את מצב הבקשה שלנו.

אם readyState
שווה ל -4, המשמעות היא שהבקשה נעשית. readyState
יש הרכוש 5 תגובות. למידע נוסף על כך כאן.
מלבד ביצוע שיחת Ajax ישירות עם JavaScript, ישנן שיטות אחרות חזקות יותר לביצוע שיחת HTTP, כמו $.Ajax
שיטת jQuery. אני אדון בזה עכשיו.
שיטות jQuery
ל- jQuery שיטות רבות לטיפול בקלות בבקשות HTTP. על מנת להשתמש בשיטות אלה, יהיה עליך לכלול את ספריית jQuery בפרויקט שלך.
$ .ajax
jQuery Ajax היא אחת השיטות הפשוטות ביותר לביצוע שיחת HTTP.

לשיטת $ .ajax נדרשים פרמטרים רבים, חלקם נדרשים ואחרים אופציונליים. הוא מכיל שתי אפשרויות התקשרות success
ו error
לטפל התגובה שקיבל.
שיטת $ .get
שיטת $ .get משמשת לביצוע בקשות GET. נדרשים שני פרמטרים: נקודת הקצה ופונקציה להתקשרות חוזרת.

$ .הודעה
$.post
השיטה היא דרך נוספת לפרסם נתונים לשרת. נדרשים שלושה פרמטרים: url
הנתונים, הנתונים שאתה רוצה לפרסם ופונקציה להתקשרות חוזרת.

$ .getJSON
$.getJSON
השיטה היחידה מאחזרת נתונים בפורמט JSON. נדרשים שני פרמטרים: url
פונקציית ו- callback.

ל- jQuery יש את כל השיטות הללו לבקש או לפרסם נתונים לשרת מרוחק. אך למעשה ניתן להכניס את כל השיטות הללו לאחת: $.ajax
השיטה, כפי שנראה בדוגמה שלהלן:

לְהָבִיא
fetch
הוא ממשק API רב-עוצמה חדש המאפשר לך להגיש בקשות אסינכרוניות. למעשה, fetch
היא אחת הדרכים הטובות והאהובות עלי ביותר להגיש בקשת HTTP. הוא מחזיר "הבטחה" שהוא אחד המאפיינים הנהדרים של ES6.אם אינך מכיר את ES6, תוכל לקרוא על כך במאמר זה. הבטחות מאפשרות לנו לטפל בבקשה האסינכרונית בצורה חכמה יותר. בואו נסתכל כיצד fetch
עובדת טכנית.

fetch
הפונקציה לוקחת פרמטר נדרש אחד: endpoint
URL. יש לו גם פרמטרים אופציונליים אחרים כמו בדוגמה שלהלן:

כפי שאתה יכול לראות, 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].