Javascript Fetch

Code Snippets Fetch


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):

async function makeRequest(){
let response = await fetch("");
let data = await response.json();

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 = "";
//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.
console.log("Fetch successful.")
//Get the json.
let json = await response.json();
//Call the callback and pass give it the body data.
console.log("Fetch error: Status Code: " + response.status + " Text: " + response.statusText);
//Displays data.
function display(data){

Resulting output:


Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger