![]() |
In JavaScript, there are many different ways to send the request to a server or database from the front end of an application. Here’s a quick reference to all the methods to send a request using JavaScript. These are the following approaches to creating a request: Table of Content JavaScript XMLHttpRequestIt is an object that is used to send the HTTP request to a server or API in JavaScript. It was widely used before the introduction of ES6. Syntax:const xhr = new XMLHttpRequest(); Parameters:
Return Value:It returns the required data if the request is of GET type. Note: you need to install XMLHttpRequest to run this code, for that, you have to run this command in your terminal: npm i XMLHttpRequest
Example: The below code illustrates how you can use the XMLHttpRequest object to send the request. Javascript
JavaScript fetch() APIThe JavaScript fetch() api can also be used to send requsets to the server to get or post the data. By default, It will send the GET request if no request type is passed. Syntax:fetch('api_address', 'request_type').then().then().catch();
Example: The below example implements the fetch() api to send the api request. Javascript
JavaScript AxiosAxios is another method of sending the request to the server. It can be easily installed using the npm command “npm install axios”. It is used with the JavaScript libraries or frameworks like React. There is no need to specify GET or POST request types because it uses get() and post() methods for the corresponding request. Syntax:axios.get('api_address').then().catch();
Example: The below example uses the axios to send the request in JavaScript. Javascript
JavaScript Async AwaitAsync Await is a method to send the requests without using the callback functions, instead make the requests to wait until the first step completes. Syntax:async function func_name(){ Example: The below example will explain the use of async await to send the request. Javascript
|
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |