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:
JavaScript XMLHttpRequest
It 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();
xhr.open('request_type', 'api_address', 'true');
xhr.send();
xhr.onload = () => {}
Parameters:
- request_type: It specifies the type of request to be sent to the server. It can be POST or GET.
- api_address: It is the URL of the server to which the specified request will be sent.
- true/false: true specifies the request is asynchronous while false specifies the request is synchronous.
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
const xhr = new XMLHttpRequest();
xhr.open('GET', 'api_address', true);
xhr.send();
xhr.onload = () => {
if (xhr.status === 200) {
const response = JSON.parse(xhr.response);
} else {
// Handle error
}
}
The 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
fetch('api_address')
.then((response)=>{
if(response.ok){
return response.json();
}
else{
throw new Error('Something went wrong!');
}
})
.then((data)=>{
console.log(data);
})
.catch((error)=>{
console.error(error);
});
JavaScript Axios
Axios 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
import axios from 'axios';
axios.get('api_address')
.then((response)=>{
const result = response.data;
})
.catch((error)=>{
console.error(error);
});
JavaScript Async Await
Async 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(){
try{
// Call api using await
}
catch(error){
// Handle Errors
}
}
Example: The below example will explain the use of async await to send the request.
JavaScript
async function fetchDataUsingAsyncAwait(){
try{
const api_data = await fetch('api_URL');
const api_json_data = await response.json();
}
catch(error){
console.error(error);
}
}
fetchDataUsingAsyncAwait();
Similar Reads
Working with APIs in JavaScript An API is simply a medium to fetch or send data between interfaces. Let's say you want to make an application that provides the user with some real-time data fetched from the server or maybe even allows you to modify or add data to some other endpoint. This is made possible by the API or the Applica
5 min read
4 Ways to Make an API Call in JavaScript API(Application Programming Interface) is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data, and interact with each other. API is a service created for user applications that request data or some functionality from servers.To
7 min read
Top Web API Interview Questions and Answers (2024) Web APIs, or Web Application Programming Interfaces, are interfaces that allow different software applications to communicate and interact with each other over the Internet. They define a set of rules and protocols that enable one application to request and exchange data or perform actions on anothe
15+ min read
Cowsay in Nodejs using Requests library Prerequisites: Basic knowledge of NodeJS and JavaScript. Also, you should have NodeJS installed on your machine.Using npm. A good resource. npm will get installed with NodeJS itself.Basic knowledge of command line or terminal. Essentially, we are going to use the requests library to make an API call
3 min read
What are the properties of XMLHttpRequest ? In this article, we will see what is XMLHttpRequest Object, along with knowing their properties with their implementation through the illustrations. XMLHTTPRequest object is an API that is used for fetching data from the server. XMLHTTPRequest is basically used in Ajax programming. It retrieves any
5 min read