About
In this code snippet, we’ll learn how to make HTTP requests with fetch in Javascript.
The first example will demonstrate how to fetch a get request with the minimum amount of code required. In the second one, we’ll make a function that can make any generic HTTP request, can send headers and checks for a successful response before calling the provided callback function.
Note: These days you can use fetch() and JSON as a replacement for AJAX(Asynchronous JavaScript And XML) and the XMLHttpRequest.
Let’s see the examples below.
Simplest Way to Make A Request(Get):
makeRequest();
async function makeRequest(){
let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let data = await response.json();
console.log(data);
} Resulting output:
Generic HTTP Requests:
The below defined makeRequest() function can make a generic HTTP request asynchronously. You simply need to pass it the URL to be called, HTTP request settings and a callback function which will be called upon the request completion(and will receive the data from the request). The requestProperties object contains: method type, headers and a body(if needed).
///////////////////////////////////////////////////////////
//Mock API url.
const url = "https://jsonplaceholder.typicode.com/posts";
//Json payload.
const json = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
});
//Here the method type, headers and body content can be set.
const requestProperties = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: json
};
//Make request.
makeRequest(url, requestProperties, display);
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//Request function.
async function makeRequest(url, requestProperties, callback) {
//Make request and await response.
let response = await fetch(url, requestProperties);
//Here we'll make sure the request was successful.
if(response.ok){
console.log("Fetch successful.")
//Get the json.
let json = await response.json();
//Call the callback and pass give it the body data.
callback(json);
}else{
console.log("Fetch error: Status Code: " + response.status + " Text: " + response.statusText);
}
}
//Displays data.
function display(data){
console.log(data);
}
///////////////////////////////////////////////////////////





